【问题标题】:jQuery Refresh/Reload Page if Ajax Success after predicted time如果 Ajax 在预测时间后成功,则 jQuery 刷新/重新加载页面
【发布时间】:2015-02-23 14:22:08
【问题描述】:

我使用 Jquery 发出 Ajax 请求。服务器返回值为“true or false”的 Json 对象,如下所示:

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

如果服务器返回true,有什么方法可以在5秒后刷新页面?

【问题讨论】:

    标签: jquery ajax


    【解决方案1】:

    在您的 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); 
       }
    }
    

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

    【讨论】:

    • 5000是什么意思..?
    • @BalaKarthik 以毫秒为单位的时间,等于 5 秒。
    • 5000 表示 5000 毫秒(1 秒 = 1000 毫秒)
    【解决方案2】:
    location.reload();
    

    您可以在if 条件中使用reload 功能成功,条件成功后页面将重新加载。

    【讨论】:

    • 重新加载页面是个好主意,但这里的重点是 setTimeout 函数:)
    【解决方案3】:
    if(success == true)
    {
      //For wait 5 seconds
      setTimeout(function() 
      {
        location.reload();  //Refresh page
      }, 5000);
    }
    

    【讨论】:

      【解决方案4】:
      var val = $.parseJSON(data);
      if(val.success == true)
      {
       setTimeout(function(){ location.reload(); }, 5000);
      
      }
      

      【讨论】:

        【解决方案5】:

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

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

        【讨论】:

        • 它适用于我,但 roload on loop 有没有办法让它只在 Ajax 值更改时才起作用
        • @SaidErraoudy 你可以让if statement 来检查值是否改变了
        • 类似的东西:jsfiddle.net/wLyoqrme/1
        • @SaidErraoudy 创建一个全局标志变量,并在您从服务器获得结果时设置它的值。然后将当前结果与之比较
        【解决方案6】:
        $.ajax("youurl", function(data){
            if (data.success == true)
            setTimeout(function(){window.location = window.location}, 5000); 
            })
        )
        

        【讨论】:

          【解决方案7】:

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

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

          让我知道你的想法。

          【讨论】:

          • setTimeout 函数只调用一次,setInterval 会被调用多次。你知道在这种情况下哪个更合适更好
          【解决方案8】:

          随便用

              $.ajax({
                  success: function (response) {
                      location.reload();
                      },
                  error : function(xhr,errmsg,err) {
                  console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
              }
              });
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2018-05-09
            • 2011-12-14
            • 2021-11-19
            • 1970-01-01
            • 1970-01-01
            • 2016-10-09
            • 2019-11-20
            • 1970-01-01
            相关资源
            最近更新 更多