2014-09-02 49 views
1

。语法如下:使用JQuery处理错误当我使用JQuery <a href="http://api.jquery.com/jquery.when/" rel="nofollow">when</a>时

$.when(
    // Get the HTML 
    $.get("/feature/", function(html) { 
    globalStore.html = html; 
    }), 

    // Get the CSS 
    $.get("/assets/feature.css", function(css) { 
    globalStore.css = css; 
    }), 

    // Get the JS 
    $.getScript("/assets/feature.js") 

).then(function() { 

    // Add CSS to page 
    $("<style />").html(globalStore.css).appendTo("head"); 

    // Add HTML to page 
    $("body").append(globalStore.html); 

}); 

我的问题

  1. 我该怎么办错误处理时异常调用服务器的测试结果(故障情况)或错误处理任何其他情况下的一个?
  2. 因为我在这里发出Ajax请求,所以我如何定义Ajax请求的超时时间?
+0

你检查过吗? – 2014-09-02 08:03:16

回答

2

deferred.then(doneCallbacks, failCallbacks)可以采取过滤器失效像

$.when(
    // Get the HTML 
    $.get("/feature/", function(html) { 
    globalStore.html = html; 
    }), 

    // Get the CSS 
    $.get("/assets/feature.css", function(css) { 
    globalStore.css = css; 
    }), 

    // Get the JS 
    $.getScript("/assets/feature.js") 

).then(function() { 

    // Add CSS to page 
    $("<style />").html(globalStore.css).appendTo("head"); 

    // Add HTML to page 
    $("body").append(globalStore.html); 

}, function(){ 
    //there is an exception in the request 
}); 

要设置超时,你可以使用timeout选项。

您可以使用它在全球像

jQuery.ajaxSetup({ 
    timeout: 5000 
}) 

或与timeout选项

+0

感谢您的快速回复。我需要为每个请求应用超时期限。在这种情况下,'JQuery.ajaxSetup'不起作用。 – SharpCoder 2014-09-02 08:10:19

+0

@SharpCoder在这种情况下,你可以使用我建议的第二个选项 – 2014-09-02 08:10:58

0

我认为这是因为调用是异步使用$.ajax()而不是短版$.get()。使用时:

$.ajax({ 
      url: "file.php", 
      type: "POST", 
      async: false, 
      success: function(data) { 

      } 
    }); 

该呼叫是同步的。

相关问题