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条)

报告相同问题?