Jquery window.location.reload();无法控制地重新加载页面?

Jquery window.location.reload();无法控制地重新加载页面?,jquery,json,Jquery,Json,有人能解释为什么会这样吗?这是我的代码: <script> $(document).ready(function() { refresh(); }); function refresh() { $.getJSON('getMessageDetails.php', function (json) { //alert(json.length); //$("#subject1").html(json[0].subject);

有人能解释为什么会这样吗?这是我的代码:

<script>
$(document).ready(function()
{
    refresh();
});

function refresh()
{      
    $.getJSON('getMessageDetails.php', function (json) {
        //alert(json.length);
        //$("#subject1").html(json[0].subject);
        //$("#unique_code1").html(json[0].unique_code);  
        $("#msg_id").html(json[0].id);
        $("#subject").html(json[0].subject);
        $("#unique_code").html(json[0].unique_code);  
        if (json.length > 0 )
        {
            //alert(json.length);
            window.location.reload(); 
        }     
        else
        {
            //do something
        } 
    }); 
    window.setTimeout(refresh,30000);
}
</script>

$(文档).ready(函数()
{
刷新();
});
函数刷新()
{      
$.getJSON('getMessageDetails.php',函数(json){
//警报(json.length);
//$(“#subject1”).html(json[0].subject);
//$(“#唯一的_代码1”).html(json[0]。唯一的_代码);
$(“#msg_id”).html(json[0].id);
$(“#subject”).html(json[0].subject);
$(“#唯一_代码”).html(json[0]。唯一_代码);
如果(json.length>0)
{
//警报(json.length);
window.location.reload();
}     
其他的
{
//做点什么
} 
}); 
设置超时(刷新,30000);
}
我想做的是,如果json中出现了新消息,那么请重新加载页面,如果没有新消息,请继续检查

现在发生的是一条新消息出现,屏幕开始疯狂地闪烁! 它必须重新加载一次,然后每30秒检查一次。需要帮忙吗?谢谢。

我想你应该:

$(document).ready(function()
{
    var int = setInterval(refresh,30000);
});

function refresh()
{      
$.getJSON('getMessageDetails.php', function (json) {
 //alert(json.length);
 //$("#subject1").html(json[0].subject);
 //$("#unique_code1").html(json[0].unique_code);  
 $("#msg_id").html(json[0].id);
 $("#subject").html(json[0].subject);
 $("#unique_code").html(json[0].unique_code);  
 if (json.length > 0 )
 {
    //alert(json.length);
    window.location.reload(); 
 }     
 else
 {
    //do something
 } 
 }); 

 }

我认为您正在寻找
setInterval
,因为听起来好像您希望每30秒调用一次函数,而不是重新加载整个页面(这就是
window.location.reload
所做的)

例如:

function sayHello(){
alert('hello once again');
}
setInterval(sayHello,30000);

因此,您需要做的是将AJAX调用包装在一个函数中,然后应用一个
setInterval
,定义它何时被重复

函数refresh from window.setTimeout的定义在哪里?还包括window.location.reload();应该从window.setTimeouti顶部发布的完整脚本运行:)如果它仍在闪烁,则json.length可能大于0?您发布的代码似乎不会导致这种情况。。“do something”代码是什么?“do something”稍后将被编码,因此其他部分是空的..我想重新加载整个页面(好像单击了刷新按钮),但只有当json.length>0时,才会出现新消息,并且每30000次检查一次新消息:)您能描述一下“闪烁”吗然后,如果它看起来不是重新加载的话?我所知道的是,它一直在执行window.location.reload();速度如此之快以至于屏幕变为空白并且没有停止..我必须关闭pageDoes
window.location.reload()是否出现在代码的其他地方?那么这一定是所有罪恶的根源(首先尝试注释它)。你也试过用另一个答案中的方法,用间隔代替超时吗?AJAX调用是否返回正确的结果?