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


Getting random number from php file using ajax wont update with new result

我正在胡思乱想我认为可能是一件简单的事情,那就是使用 jquery ajax 生成随机数。我有一个索引.php它轮询生成器.php随机数,代码如下

索引.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>

发电机.php :

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

所以这在第一次加载时工作正常,它从 generator 获取随机数.php但在该索引之后.php继续加载但什么也没得到,显示的数字保持不变。我在这里做错了什么?

我认为问题document.write(data.foo);.将其替换为:

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

并在 html 文档中添加一个 id 为"anId"的元素,在该脚本之前。

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

我无法用确切的代码复制您描述的内容。它只是不断将随机数附加到 body 元素。你的HTML是什么样的?

此外,如果您只想要一个介于 10 和 100 之间的随机数,您可以在没有 PHP 的情况下处理这个问题。

这是我想到的:

setInterval(function(){
  var random = Math.floor( Math.random() * 90 ) + 10;
  $('body').text(function(i,val){
    return val + random;
  });
}, 3000);

下面是一个演示:

http://jsbin.com/evOtuqA/2/edit

为什么不直接使用 Javascript 来生成一个随机数:

function randomRange(min, max) {
return ~~(Math.random() * (max - min + 1)) + min
}

或者使用:

setInterval.randomnumber()
function randomnumber(){
$.ajax({
        dataType: "json",
        type: "POST",
        url: ('./generator.php'),
        success: function(data) {return(data)}
    }); }