如果 Ajax 成功,jQuery 刷新/重新加载页面

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27654298/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:25:56  来源:igfitidea点击:

jQuery Refresh/Reload Page if Ajax Success after time

jqueryajax

提问by Anh Hoang

I use Jquery to call Ajax. The server returns Json object with value "true or false" like this:

我使用 Jquery 调用 Ajax。服务器返回值为“true 或 false”的 Json 对象,如下所示:

return Json(new { success = false, JsonRequestBehavior.AllowGet });

Is there any way to refresh page after 5 seconds if the server returns true?

如果服务器返回 true,有没有办法在 5 秒后刷新页面?

回答by Jai

In your ajax success callback do this:

在您的 ajax 成功回调中执行以下操作:

success: function(data){
   if(data.success == true){ // if true (1)
      setTimeout(function(){// wait for 5 secs(2)
           location.reload(); // then reload the page.(3)
      }, 5000); 
   }
}

As you want to reload the page after 5 seconds, then you need to have a timeout as suggested in the answer.

由于您想在 5 秒后重新加载页面,因此您需要按照答案中的建议设置超时。

回答by Vikas Gautam

location.reload();

You can use the reloadfunction in your ifcondition for success and the page will reload after the condition is successful.

您可以reload在您的if条件下使用该功能成功,并且在条件成功后页面将重新加载。

回答by Sadikhasan

if(success == true)
{
  //For wait 5 seconds
  setTimeout(function() 
  {
    location.reload();  //Refresh page
  }, 5000);
}

回答by AVM

var val = $.parseJSON(data);
if(val.success == true)
{
 setTimeout(function(){ location.reload(); }, 5000);

}

回答by asdf_enel_hak

$.ajax("youurl", function(data){
    if (data.success == true)
    setTimeout(function(){window.location = window.location}, 5000); 
    })
)

回答by Nick Coleby

Lots of good answers here, just out of curiosity after looking into this today, is it not best to use setIntervalrather than the setTimeout?

这里有很多很好的答案,只是出于好奇,在今天研究了这个之后,最好使用setInterval而不是setTimeout?

setInterval(function() {
location.reload();
}, 30000);

let me know you thoughts.

让我知道你的想法。

回答by A. El-zahaby

I prefer this way Using ajaxStop+ setInterval,, this will refresh the page after any XHR[ajax]request in the same page

我更喜欢这种方式使用ajaxStop+ setInterval,,这将在同一页面中的任何XHR[ajax]请求后刷新页面

    $(document).ajaxStop(function() {
        setInterval(function() {
            location.reload();
        }, 3000);
    });