javascript - 按下 HTML 按钮时如何显示从 PHP 函数返回的数据
问题描述
我想在我的页面中显示从 PHP 函数生成的装置,但只有当我按下“生成装置”按钮时。我知道应该使用 AJAX,但我无法将函数中的数据传递给 HTML 页面中的 div。
PHP 代码
$teams = array("FC FCSB", "AFC Astra Giurgiu", "FC Dinamo 1948", "FC Viitorul 2009", "CSM Politehnica Iasi", "Universitatea Craiova", "FC Botosani", "CFR 1907 Cluj");
$fixPair = new Fixture($teams);
$schedule = $fixPair->getSchedule();
$i = 1;
foreach ($schedule as $rounds) {
echo "<h5> Etapa " . $i . " </h5>";
foreach ($rounds as $game) {
echo "{$game[0]} vs {$game[1]}<br>";
}
echo "<br>";
$i++;
}
echo "<hr>";
$(document).ready(function(){
$('.button').click(function(){
var clickBtnValue = $(this).val();
var ajaxurl = 'ajax.php',
data = {'action': clickBtnValue};
$.post(ajaxurl, data, function (response) {
// Response div goes here.
document.getElementById("demo").innerHTML = "Fixtures should be displayed here";
//alert("action performed successfully");
});
});
});
<script
src="https://code.jquery.com/jquery-3.4.1.min.js">
</script>
<input type="submit" class="button" name="insert" value="GENERATE FIXTURES" />
<div id="demo"></div>
解决方案
将您的事件处理程序更新为:
$('.button').click(function(e){
// Prevent form submit
e.preventDefault();
var clickBtnValue = $(this).val();
var ajaxurl = 'ajax.php',
data = {'action': clickBtnValue};
$.post(ajaxurl, data, function (response) {
// response variable stores all data received from ajax.php script
// As you use jquery - you can select
// element by id with $("#id") selector
$("#demo").html(response);
});
});
推荐阅读
- python-3.x - 使用散景为图例添加值
- angular - 静态注入器错误
- regex - 如果存在两个或更多括号字符串,如何提取单元格末尾括号中分隔的字符串
- c - 在c中发送电子邮件,服务器在我发送正文后从不回复
- hibernate - Grails 3:GenericJDBCException:无法准备语句
- c# - 无法从 System.Collection.Generic.List 转换
给 Dal.Questio - php - 如何使用 Laravel 集合实现分页?
- java - 如何使用 BigQuery 连接器从 java spark 读取 BigQuery 表
- ruby-on-rails - 如何从 URL 下载 Internet 图像并将其保存在 Rails 本地?
- python - 如何更改docx文件python中的字体大小