我为我的项目做作业。我不得不在不刷新网页的情况下使用ajax来更新mysql。
我有2个php文件,第一个是a.php
,代码如下(查看用户信用):
if($_GET['do'] == 'viewcredit'){
$quser = DB::query("SELECT * FROM ".DB::table('game_jnship_user')." WHERE uid = '$_G[uid]'");
$ruser = DB::fetch($quser);
//$moneyN = $ruser['money'];
echo $ruser['money'];
}
第二个php文件是b.php
,代码如下(执行一些操作):
$quser = DB::query("SELECT * FROM ".DB::table('game_jnship_user')." WHERE uid = '$_G[uid]'");
$ruser = DB::fetch($quser);
$moneyN = $ruser['money'];
$gcoin = $ruser['gcoin'];
if($_GET['do'] == 'treasurehunt'){
$moneyadd = $moneyN + 1;
DB::query("UPDATE ".DB::table('game_jnship_user')." SET money = '$moneyadd' WHERE uid = '$_G[uid]'");
}
我的html
代码如下:
<script src="https://code.jquery.com/jquery-1.12.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>jQuery.noConflict();</script>
<script>
jQuery(function() {
jQuery(".submit_button").click(function() {
var url = "a.php?do=viewcredit";
var decodedUrl = decodeURIComponent(url);
jQuery.ajax({
type: "POST",
url: decodedUrl,
cache: true,
success: function(html){
jQuery("#money").html(html);
}
});
});
});
</script>
<div id="money">$ruser[money]</div>
<a href="javascript:;" onclick="showWindow('jn_spop', 'b.php?do=treasurehunt')" class="c_button submit_button"><strong>Confirm</strong></a>
所以,现在,当我第一次单击html
的最后一行,即<a>Confirm</a>
时,<div id="money">$ruser[money]</div>
将不会给出最新的结果。
好的,比方说$ruser[money] = '1';
,在我点击<a>Confirm</a>
之后,mysql已经将money
更新为2
,但<div id="money">$ruser[money]</div>
仍然显示1。在我再次点击<a>Confirm</a>
之后,<div id="money">$ruser[money]</div>
显示2
(但mysql已经将money
更新为3
。)
那么,如果我想用ajax
延迟来做a.php?do=viewcredit
,这可能吗?有没有其他方法可以在不刷新网页的情况下获得最新的$ruser[money]
?
谢谢。
您可以设置async:false。但是,如果您的ajax请求需要一些时间来显示一些加载程序,这样用户就会理解正在执行的一些操作。有关更多详细信息,请查看此链接:http://api.jquery.com/jquery.ajax/
jQuery.ajax({
type: "POST",
url: decodedUrl,
cache: true,
async: false,
success: function(html){
jQuery("#money").html(html);
}
});