dounei5721 2013-10-06 14:56
浏览 24
已采纳

使用ajax从php文件中获取随机数不会更新新结果

I am mucking around with what I thought might be a simple thing to do, which is generate random numbers using jquery ajax. I have an index.php that polls generator.php for a random number and the code is as follows

index.php :

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
setInterval(function(){
$.ajax({ url:'./generator.php', cache : false, success: function(data){
    document.write(data.foo);
}, dataType: "json"});
}, 3000);   
</script>

generator.php :

<?php
$x = rand(10,100);
$array = array(
    'foo'  => $x    
);
echo json_encode($array);
?>

So this works fine on the first load, it gets the random number from generator.php but after that index.php continues to load but gets nothing at all and the number displayed stays the same. What am I doing wrong here?

  • 写回答

3条回答 默认 最新

  • douxing7101 2013-10-06 15:21
    关注

    I think the problem is document.write(data.foo);. Replace it with:

    document.getElementById('anId').innerHTML = data.foo;
    

    And add an element with id of "anId" in your html document, before that script.

    <div id="anId"></div>
    <script type="text/javascript">
    setInterval(function(){
    $.ajax({ url:'./generator.php', cache : false, success: function(data){
        document.getElementById('anId').innerHTML = data.foo;
    }, dataType: "json"});
    }, 3000);   
    </script>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 matlab有关常微分方程的问题求解决
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法