2012-11-14 20 views
2

我有這個JSONP功能:如何接收通知的404409和其他服務器錯誤的JSONP調用

function jsonp(url, callback) { 
    var script = document.createElement("script"); 
    script.setAttribute("type","text/javascript"); 
    script.setAttribute("onerror","javascript:DisplayPopUp('','staleExceptionRefresh')"); 
    script.setAttribute("src", url + questionMark + "accept=jsonp&callback="+callback + "&cachebuster="+new Date().getTime()); 
    document.getElementsByTagName("head")[0].appendChild(script); 
} 

我趕上這樣的成功事件:

function someCallbackFunction(data1, data2) {} 

但問題是,如果我得到404或409或其他服務器錯誤,我不知道如何捕捉它們(它們不出現在someCallbackFunction上)。

我可以設置一個onerror屬性來顯示一些內容,但是如何捕獲服務器的響應。

這是服務器響應,我不能夠趕上與我的正常回調函數的例子:

DeleteWebsiteAjaxCall({"action":"", "type":"", "callerId":""}, {errorDescription: "important description I want to display","success":false,"payload":null}); 

如何釣上的功能這些錯誤(陳舊例外?)?

回答

2
function jsonp(url, callback) { 
    var script = document.createElement("script"); 
    script.setAttribute("type","text/javascript"); 
    script.setAttribute("src", url + questionMark + "accept=jsonp&callback="+callback + "&cachebuster="+new Date().getTime()); 
    var errHandler = function(evt) { 
     clearTimeout(timer) 
     // reference to http://www.quirksmode.org/dom/events/error.html 
     // you will get an error eventually, and you can call callback manually here, to acknowledge it. 
     // but unfortunately, on firefox you can get error type as undefined, and no further detail like error code on other browser either. 
     // And you can tell the callback function there is a net error (as no other error will fire this event.) 
     window[callback](new Error()); 
    }; 
    script.onerror = errHandler; 
    script.onload = function() { 
     clearTimeout(timer); 
    } 
    // also setup a timeout in case the onerror failed. 
    document.getElementsByTagName("head")[0].appendChild(script); 
    var timer = setTimeout(errHandler, 5000); 
} 

如果您的服務器將在404/409發生時做出響應,則將200狀態碼發送給客戶端,以便對腳本進行評估。

否則,瀏覽器將忽略服務器響應和火災事件。

相關問題