[英]How do I update javascript variables with new values which are changing in my database?
I'm building a multiplayer game which uses a mysql database to store coordinate positions of players, which are then used to display opponent models. 我正在构建一个使用mysql数据库存储玩家坐标位置的多人游戏,然后将其用于显示对手模型。
The game uses a javascript file (milktruck.js) on the client side, and then a php file (xml_http_request.php) on the server side. 该游戏在客户端使用javascript文件(milktruck.js),然后在服务器使用php文件(xml_http_request.php)。
My problem occurs when trying to get the javascript variables (which store the coordinate information of an opponent) updated as the database information is updated. 尝试获取随着数据库信息更新的javascript变量(存储对手的坐标信息)时发生我的问题。
The javascript variables are declared within the php file with the following code: javascript变量在php文件中用以下代码声明:
echo "<script> var lla0php = $lla0; </script>";
echo "<script> var lla1php = $lla1; </script>";
echo "<script> var lla2php = $lla2; </script>";
Then used in the javascript file, ticking function: prototype.tick, with: 然后在javascript文件中使用的勾号函数:prototype.tick,带有:
window['lla0_2']= lla0php;
window['lla1_2']= lla1php;
window['lla2_2']= lla2php;
How do I continuously update these variables with new database information? 如何使用新的数据库信息不断更新这些变量?
The web model is stateless, and to do this you're going to have to think of a way to overcome this and may possibly consider writing an abstraction layer that takes care of this for you. Web模型是无状态的,要做到这一点,您将不得不考虑一种克服该问题的方法,并可能考虑编写一个抽象层来为您解决这个问题。
You'll either need to poll continuously or look into other web-based solutions that allow the server to "push" data back to the client and maintain an "open channel" of communication. 您将需要连续轮询或研究其他基于Web的解决方案,这些解决方案允许服务器将数据“推”回客户端并保持“开放渠道”的通信。 An example of this would be Google Talk in your browser or FaceBook chat.
例如浏览器中的Google Talk或FaceBook聊天。
What you need to do is use ajax. 您需要做的是使用ajax。
function requestCoord(){
$.ajax({
url: "your url",
dataType : "json",
type: "GET",
success(val){
//get your php script to echo out a json string
//and it will be in val
window['lla0_2']= val.lla0php;
window['lla1_2']= val.lla1php;
window['lla2_2']= val.lla2php;
}
});
}
setInterval(requestCoord, 1000);
You can use html5 sockets. 您可以使用html5套接字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.