2

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

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

4

1 回答 1

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

于 2012-11-14T12:20:10.057 回答