[英]Updating webpage with real-time database value using AJAX+PHP response
I'm creating a Javascript game and I'm currently trying to write some code that will show the player's “Gold Balance” in real time on a html webpage. 我正在创建一个Javascript游戏,当前正在尝试编写一些代码,这些代码将在html网页上实时显示玩家的“黄金余额”。
The Gold amount is contained in my SQL database, so I'm using setInterval
with a Javascript function that contains an AJAX call which calls a PHP script that grabs the current balance amount for the player and sends it back as “response”. 黄金数量包含在我的SQL数据库中,因此我将
setInterval
与Javascript函数结合使用,该函数包含一个AJAX调用,该调用调用一个PHP脚本,该脚本获取播放器的当前余额并将其作为“响应”发送回去。
I'm able to have this amount appear as a Javascript alert, however I need to have the response appear as text on the webpage inside a <div>
instead. 我可以将这个金额显示为Javascript警报,但是我需要将响应显示为
<div>
内网页上的文本。
This is my current code: 这是我当前的代码:
<script>
setInterval("checkGold()",5000);
function checkGold()
{
$.ajax({
url: 'scripts/checkGold.php',
data: "",
dataType: 'json',
success: function(response){
alert(response);
}});
};
</script>
I have this in my html source code, I would like to place the function in a separate file and call it from there, but when I tried this I wasn't able to send the response back to the html page correctly. 我在html源代码中有此功能,我想将该函数放在一个单独的文件中并从那里调用它,但是当我尝试执行此操作时,我无法将响应正确发送回html页面。
I was wondering if anyone knows how to have this response appear as text on the page inside <div> </div>
? 我想知道是否有人知道如何在
<div> </div>
内的页面上以文本形式显示此响应?
Also, I was wondering if this method will really update the div in real time (ie, will it auto-refresh the div part of the webpage, showing an up to date value (every 5000 milliseconds)? 另外,我想知道这种方法是否真的可以实时更新div(即,它会自动刷新网页的div部分,显示最新值(每5000毫秒)吗?
Thanks in advance! 提前致谢!
Since you are using jQuery, you can use text() to alter the contents of an existing div (which id is "yourDiv"): 由于您使用的是jQuery,因此可以使用text()更改现有div(其ID为“ yourDiv”)的内容:
setInterval("checkGold()",5000);
function checkGold()
{
$.ajax({
url: 'scripts/checkGold.php',
data: "",
dataType: 'json',
success: function(response){
$('div#yourDiv').text(response);
}
});
};
You have two questions here, so I will try to address both 您在这里有两个问题,所以我会尽力解决
1) How to append to the DOM using jQuery, instead of an alert: 1)如何使用jQuery而不是警报附加到DOM:
in the success callback function, instead of alerting the response, you can simply call 在成功回调函数中,您可以简单地调用而不是警告响应
$('body').append("<div>"+response+"</div>")
2) "Real time" Gold Balance 2)“实时”黄金余额
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.