2014-09-02 120 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) { 

      } 
    }); 

該呼叫是同步的。

相關問題