当我点击按钮,它应该显示计数值(从数据库)下面的按钮
<button id="update">update</button>
<script>
$(document).ready(function() {
$('#update').click(function(){
var complete = 0;
$.ajax({
type: "POST",
URL: "functions/doneex.php",
data: {
complete: complete
},
success: function(res) {
//alert(res);
}
});
});
})
</script>
<?php
echo $res ;
?>
(get value from db)它被ajax调用
doneex.php
$query=$conn->prepare("SELECT COUNT(isdone) AS complete FROM $today_workout_tbl WHERE isdone=1");
$query -> execute();
$query -> bind_result($complete);
$query -> fetch();
$query -> close();
echo $complete;
在PHP中,您可以使用内置的gobals数组访问post请求中传递的数据:
$res = $_REQUEST['res']
要将它们包含到ajax请求中,您需要:检索
表单元素的值,例如:
var valueOfResField = $('[name=res]')。值
并通过ajax请求发送:
$.ajax({
type: "POST",
URL:"functions/doneex.php",
data:{complete :complete, res: valueOfResField},
success:function(res){
//alert(res);
$("#done").html(res);
}});
如果希望在PHP中处理这个变量值并将修改后的值返回到表单中,则必须将该值存储在服务器上,然后调用ajax再次检索该值,并在显示的html页面中修改该值。
这个问题很模糊,但我认为你想看看设置你的。ajax调用的数据类型为JSON,然后使用json_encode(…)从PHP脚本返回数据。这是获取从PHP脚本(在示例中为donexx . PHP)返回的数据的简单(且易读)方法。
下面是一个例子:
Javascript:$.ajax({
url: '/ajax/do_php_stuff.php',
type: 'POST',
data: 'pid=' + personid ,
dataType: 'json',
success: successCallback
});
function successCallback(response, status) {
if (response.ok) {
alert(response.data);
}
}
PHP (/ajax/do_php_stuff.php) <?php
echo json_encode(Array('ok' => true, 'data'='hello');
?>
将此应用于您的更新问题:
<button id="update">update</button>
<script>
$(document).ready(function() {
$('#update').click(function(){
var complete = 0;
$.ajax({
type: "POST",
URL: "functions/doneex.php",
data: {
complete: complete
},
dataType: 'json'
success: function(res) {
alert(res.complete);
}
});
});
})
</script>
<?php
echo $res ;
?>
(get value from db)它被ajax调用
doneex.php
$query=$conn->prepare("SELECT COUNT(isdone) AS complete FROM $today_workout_tbl WHERE isdone=1");
$query->execute();
$query->bind_result($complete);
$query->fetch();
$query->close();
echo json_encode(Array('complete' =>$complete));
但是第一个脚本中的"echo $res"将在脚本输出时呈现,这是在ajax运行之前,…所以这部分是行不通的。如果您正在运行PHP,那么您应该将donexx . PHP中的内容包装到一个函数中,然后从两个脚本中调用它!或者,如果你想让它在点击按钮时更新,那么将值放在a中,并使用jQuery设置div内的文本,使用.text()