duanhao1004 2015-04-29 18:14
浏览 80

使用AJAX + PHP响应更新具有实时数据库值的网页

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.

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”.

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.

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.

I was wondering if anyone knows how to have this response appear as text on the page inside <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)?

Thanks in advance!

  • 写回答

2条回答 默认 最新

  • dqpfl2508589 2015-04-29 18:26
    关注

    Since you are using jQuery, you can use text() to alter the contents of an existing div (which id is "yourDiv"):

    setInterval("checkGold()",5000); 
    
    function checkGold()
    {
        $.ajax({
          url: 'scripts/checkGold.php',
          data: "",
          dataType: 'json',
          success: function(response){
            $('div#yourDiv').text(response);       
          }
        });
    };
    
    评论

报告相同问题?

悬赏问题

  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器