【问题标题】:jQuery getJSON with timeoutjQuery getJSON 超时
【发布时间】:2011-05-07 12:16:45
【问题描述】:

当调用 yahoo Web 服务 (http://boss.yahooapis.com/ysearch) 以返回数据集时,是否可以设置超时并在超时后退出例程?

jQuery.getJSON("http://boss.yahooapis.com/ysearch/...etc",
        function (data) {
              //result set here
            });

【问题讨论】:

    标签: jquery timeout getjson


    【解决方案1】:

    您可以使用超时选项

    http://api.jquery.com/jQuery.ajax/

    $.ajax({
      url: url,
      dataType: 'json',
      data: data,
      success: callback,
      timeout: 3000 //3 second timeout
    });
    

    【讨论】:

    • 谢谢!触发超时的回调是什么?
    • 不,那是 ajax 调用返回的时候……那个回调函数会被调用
    • 非常好,但是如何将事件处理程序设置为超时?
    【解决方案2】:
     $.ajax({ 
      url: url, 
      dataType: 'json', 
      data: data, 
      success: callback, 
      timeout: 3000 //3 second timeout, 
      error: function(jqXHR, status, errorThrown){   //the status returned will be "timeout" 
         //do something 
      } 
    }); 
    

    【讨论】:

      【解决方案3】:
          function testAjax() {
              var params = "test=123";
              var isneedtoKillAjax = true; // set this true
      
              // Fire the checkajaxkill method after 10 seonds
              setTimeout(function() {
                  checkajaxkill();
              }, 10000); // 10 seconds                
      
              // For testing purpose set the sleep for 12 seconds in php page 
      
              var myAjaxCall = jQuery.getJSON('index2.php', params, function(data, textStatus){               
                  isneedtoKillAjax = false; // set to false
                  // Do your actions based on result (data OR textStatus)
              }); 
      
              function checkajaxkill(){
      
                  // Check isneedtoKillAjax is true or false, 
                  // if true abort the getJsonRequest
      
                  if(isneedtoKillAjax){
                      myAjaxCall.abort();
                      alert('killing the ajax call');                 
                  }else{
                      alert('no need to kill ajax');
                  }
              }
          }
      

      【讨论】:

      • 我喜欢这个答案的创造性。我实际上不知道我可以以这种方式中止 getJSON 调用,所以谢谢。这适用于我们的应用程序。
      【解决方案4】:

      Galen 提出的超时选项是最好的方法。如果您想要一种替代方法,您可以记录发起请求的时间,并在您的回调中将其与当前时间进行比较。如果经过一定时间,则忽略结果。当然这不会取消请求。

      【讨论】:

        猜你喜欢
        • 2012-12-23
        • 2023-03-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-20
        • 2010-12-09
        • 2013-08-10
        • 2013-05-26
        相关资源
        最近更新 更多