Как получить уведомление о 404,409 и других ошибках сервера при вызове jsonp
У меня есть эта функция 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});
Как я могу поймать эти ошибки (устаревшие исключения?!) в функции?
1 ответ
Решение
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.