2011-04-11 76 views
5

我插入script標籤到像這樣的DOM(認爲JSONP):什麼HTTP頭/響應觸發腳本標記上的「onerror」處理程序?

var s = document.createElement('script'); 
s.src = "http://abc.com/js/j.js"; 
s.onerror = function() { 
    alert("Error loading script tag!"); 
}; 
document.getElementsByTagName('head')[0].appendChild(s); 

現在,我知道從abc.com一個404爲響應上面的腳本會觸發事件...什麼其他頭/響應會導致script標記發生錯誤?我可以想象它會因瀏覽器而有所不同,但如果任何人有任何列表,這將是非常有用的。

謝謝!

+1

當我創建並指一個PHP文件中我已經將響應代碼設置爲404,「onerror」不會觸發,而引用一個不存在的文件會拋出「onerror」。 – pimvdb 2011-04-11 18:17:10

+0

更新:可能是因爲'Content-length'仍然在我的PHP文件中發送,但似乎無法刪除它。 – pimvdb 2011-04-11 18:35:11

回答

7

4xx和5xx應該會導致錯誤 - 至少它們被定義爲錯誤代碼。

剛剛在Fx 3.5中測試過 - 這是正確的說法。

這裏的,如果你想測試其他瀏覽器的測試代碼(快速和骯髒......)

var codes = [100, 101, 102, 122, 200, 201, 202, 203, 204, 205, 206, 207, 226, 300, 301, 302, 303, 304, 305, 306, 307, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410], 411, 411, 412, 413,414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 444, 449, 450, 499, 500, 501, 502, 503, 504, 505, 506, 507, 508, 509, 510 ]; 

      $(codes).each(function() { 
       var s = document.createElement('script'); 
       s.src = "http://localhost/test.php?code="+this; 
       var cd = this; 
       s.onerror = function() { 
        document.write(cd+',') 
       }; 
       document.getElementsByTagName('head')[0].appendChild(s); 

      }); 

和PHP代碼:

<?php header('HTTP/1.0 '.$_GET['code'].' OK'); ?> 
+1

這實際上只會導致我的Chrome/Apache環境中的「407」錯誤。 – pimvdb 2011-04-11 18:55:35

+0

這是我得到使用上面的代碼在Firefox: '300,301,302,303,304,305,306,307,400,401,402,403,404,405,406,407,409,410,''408,411,412,413,414,415,416,417,418,419,420,421,422,423,424,425,426,''444,449,450,499,500,501,502,503,504,505,506,507,508,509,510,411,'但3xx的應該是因爲我不提供Location頭 – 2011-04-11 19:58:42

+0

是,在Firefox的更多錯誤拋出。不知道爲什麼。根據規格,當負載過程中出現「錯誤」時應該觸發'onerror'。我想這是依賴於瀏覽器,關於如何解釋。 http://dev.w3.org/html5/spec/scripting-1.html#script – pimvdb 2011-04-11 21:24:34

相關問題