我有以下脚本:
$(function (){
$('.press_me').click(function(){
var request = $.ajax({
type: "POST",
url: "counter.php"
});
request.done(function( msg ) {
alert('Success');
return;
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
});
});
和counter.php:
<?php
// Connection to database
$connection=mysqli_connect("host","user","pass","db");
// Check connection
if (mysqli_connect_errno())
{
echo 'NOT_OK';
//echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Increasing the current value with 1
mysqli_query($connection,"UPDATE table SET amount = (amount + 1) WHERE ID='1' ");
mysqli_close($connection);
echo 'OK'; ?>
1.为了查看更新的值,我必须重新编写页面,我认为这意味着ajax不能异步工作,这就是我想要的。我用async参数尝试了一切,但我失败了
2.我应该使用什么更新子句以便分别更新每一行,因为此状态下的代码只更新一行,或者如果省略where子句,它会更新所有行。 谁能帮我?
答案 0 :(得分:0)
回答你的两个问题:
一旦完成AJAX请求,您就不会告诉该页面如何处理结果。你所做的只是一个提示“成功”的警报。如果您希望页面使用数据库中的新amount
更新,那么您的php脚本必须将此新amount
返回给AJAX函数。请参阅下面的javascript部分,其中显示“实际更新的部分......”。在这一部分中,您将不得不放置实际更新网页HTML(DOM)的内容,而无需用户刷新网页。这可以通过javascript轻松完成。见下文。
我不确定你的意思。现在你将amount
中的table
增加1 ID='1'
,所以只有ID = 1的行数量才会增加1.我假设你有多个按钮与class='press_me'
。如果是这种情况,您必须为所有这些按钮提供不同的ID,然后将该ID传递给AJAX后调用。
所以你的按钮就是:
<button class="press_me" id="ID HERE">Click me</button>
你的javascript就是:
$('press_me').click(function(){
var button_ID= $(this).attr("id");
$.post('counter.php', {button_ID: button_ID}, function(result){
// the var 'result' is the new count of this button,
as generated by the PHP page below. Do with this var whatever
you want. If you want to show the new amount of this counter
in a div for example, you can do:
$('.counter_div').html('New count: ' + result);
});
});
你的PHP:
<?php
$connection=mysqli_connect("host","user","pass","db");
mysqli_query($connection,"UPDATE table SET amount = (amount + 1) WHERE ID='" . $_POST["button_ID"] . "'");
//Get the new count for this button, and echo it, so it can
be picked up by the AJAX call return:
$get_count= mysqli_query("SELECT * FROM `table` WHERE `ID`='" . $_POST["button_ID"] . "'");
$count_data= mysqli_fetch_array($new_count_data);
echo($count_data["amount"]);
mysqli_close($connection);
?>