我有这个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});
如何在函数上捕获这些错误(陈旧异常?!)?
答案 0 :(得分: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状态代码发送给客户端,以便对该脚本进行评估。
否则,浏览器将省略服务器响应并触发onerror事件。