2010-07-29 31 views
5

處理我周圍使用jQuery的AJAX功能的包裝功能是這樣的:jQuery的Ajax錯誤與「腳本」數據類型

$.getAjax = function(url, type, callback){ 
    $.ajax({ 
     url: url, 
     cache: false, 
     dataType: type, 

     success: function(){ 
      alert("success"); 
     }, 
     complete: function(XMLHttpRequest, textStatus){ 
      alert("complete"); 

      if (callback != undefined) { 
       callback(); 
      } 
     }, 
     error: function (XMLHttpRequest, textStatus, errorThrown){ 
      alert("error"); 
     } 
    }); 
} 

當我使用這個以「文本」作爲數據類型它完美的作品,即使網址無效。當一個url無效時,它首先調用錯誤,然後調用完整的函數。沒關係。 但是,當我使用「script」作爲dataType時,它不會在URL無效時調用任何東西。 當我使用「腳本」作爲數據類型時,我應該怎麼做以捕獲HTTP 404錯誤和其他錯誤?

+0

您用什麼來調試?你有權訪問Fiddler或Firebug,以便評估正在請求並返回的內容嗎?另一個問題是:你是否試圖通過'腳本'請求訪問不同域上的資源? – 2010-07-29 17:19:17

+0

我甚至不嘗試Firebug,但這是一個好主意。資源位於不同的域中,但我可以從「跨域」獲取腳本 – Pink 2010-07-29 17:21:22

+0

將'type'參數從'script'更改爲'jsonp'會發生什麼?你的成功警示火嗎? – 2010-07-29 21:17:41

回答

1

我看了看jQuery的源代碼,發現它沒有調用任何錯誤處理程序方法。實際上,只有當http get請求成功時才調用success()和complete()函數。

// If we're requesting a remote document 
     // and trying to load JSON or Script with a GET 
     if (s.dataType === "script" && type === "GET" && remote) { 
      var head = document.getElementsByTagName("head")[0] || document.documentElement; 
      var script = document.createElement("script"); 
      script.src = s.url; 
      if (s.scriptCharset) { 
       script.charset = s.scriptCharset; 
      } 

      // Handle Script loading 
      if (!jsonp) { 
       var done = false; 

       // Attach handlers for all browsers 
       script.onload = script.onreadystatechange = function() { 
        if (!done && (!this.readyState || 
          this.readyState === "loaded" || this.readyState === "complete")) { 
         done = true; 
         success(); 
         complete(); 

         // Handle memory leak in IE 
         script.onload = script.onreadystatechange = null; 
         if (head && script.parentNode) { 
          head.removeChild(script); 
         } 
        } 
       }; 
      } 

      // Use insertBefore instead of appendChild to circumvent an IE6 bug. 
      // This arises when a base node is used (#2709 and #4378). 
      head.insertBefore(script, head.firstChild); 

      // We handle everything using the script element injection 
      return undefined; 
     } 
0

壞消息:這個問題在jquery 1.x中仍然沒有解決。好消息:它解決了jquery 2.x(它不支持IE < = 8)。我已經設法讓我的complete回調工作,收到錯誤通知。請參閱here以獲得jquery代碼或相關代碼片段:

send: function(_, complete) { 
    script = jQuery("<script>").prop({ 
     async: true, 
     charset: s.scriptCharset, 
     src: s.url 
    }).on(
     "load error", 
     callback = function(evt) { 
      script.remove(); 
      callback = null; 
      if (evt) { 
       complete(evt.type === "error" ? 404 : 200, evt.type); 
      } 
     } 
    ); 
    document.head.appendChild(script[ 0 ]); 
},