gpt4 book ai didi

javascript - 如何在 jsonp 调用中接收 404,409 和其他服务器错误的通知

转载 作者:行者123 更新时间:2023-11-29 22:19:12 25 4
gpt4 key购买 nike

我有这个 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});

我如何在函数上捕获这些错误(过时的异常?!)?

最佳答案

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 事件。

关于javascript - 如何在 jsonp 调用中接收 404,409 和其他服务器错误的通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13377708/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com