我正在尝试制作一款没有页面刷新的实时游戏。问题是,我不知道下一步该做什么或如何配置ajax脚本更新mysql数据库时,玩家是移动在地图上。
这是我试图使用的ajax代码。
//calling ajax to update player location when he move around
function send(url){
var request;
try{
request= new XMLHttpRequest();
} catch (e){
try{
request= new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
request= new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
alert("Your browser broke!");
return false;
}
}
}
request.onreadystatechange = function(){
if(request.readyState == 4){
//I dont know what to add here :-(
}
}
request.open("GET", url, true);
request.send(null);
}
send("update_location.php?newX="+ toX + "&newY=" + toY)
update_location.php
<?php
$new_x=$_GET['newX'];
$new_y=$_GET['newY'];
//echo"$new_x , $new_y";
$update_loc=mysql_query("UPDATE users SET location_x='$new_x' WHERE username='admin'");
?>
主要理念是当玩家在地图上移动时,ajax会将新的x和y值更新到数据库中。我不需要任何按钮或jquery代码添加,我认为ajax将工作很好,如果有人给我一个手这样做。
注:toX和toY是javascript变量,我转换为php变量,所以我可以更新它们到mysql数据库。如果有人能帮我做这件事,我将非常感激!
首先理清在这种情况下要做什么。从你的描述来看,我觉得不够清楚。
如果你想做一些基于你的ajax响应,那么 onSucess
是正确的选择,而不是onreadystatechange
。
如果你想在Ajax响应上做一些事情,那么你应该从服务器端发送所需的数据,并在javascript代码中使用它来执行所需的操作。
如. .
new Ajax.Request('testurl',{
method: 'post',
parameters: {param1:"A", param2:"B", param3:"C"},
onSuccess: function(response){
//do something here
}
});