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 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭