Javascript 获取相当于jquery';s$(document.ajaxError())
有没有一种方法可以钩住与jquery的$(document.ajaxError()类似的所有fetchAPI()ajax调用错误 我们正在使用$(document).ajaxError()检测会话超时/失败并显示登录对话框。我希望在收到失败的响应后立即检测超时 下面是一些代码:Javascript 获取相当于jquery';s$(document.ajaxError()),javascript,jquery,ajax,fetch-api,Javascript,Jquery,Ajax,Fetch Api,有没有一种方法可以钩住与jquery的$(document.ajaxError()类似的所有fetchAPI()ajax调用错误 我们正在使用$(document).ajaxError()检测会话超时/失败并显示登录对话框。我希望在收到失败的响应后立即检测超时 下面是一些代码: $(document).ajaxError((event, jqxhr) => { if (jqxhr.statusText === 'abort') { retur
$(document).ajaxError((event, jqxhr) => {
if (jqxhr.statusText === 'abort') {
return;
}
// Sometimes (even with /restapi/session), we get no jqxhr.responseJSON, but we do have jqxhr.responseText
let responseJSON = jqxhr.responseJSON;
if (!responseJSON && jqxhr.responseText) {
responseJSON = JSON.parse(jqxhr.responseText);
}
if (jqxhr.status === 401) {
if (!responseJSON) {
// https://sentry.zetta.net//zetta/prod-frontend/group/13631/
alert('API call\'s responseJSON is empty, and so is jqxhr.responseText. Check the Console logs for more info.');
console.error('jqxhr:', jqxhr, 'event:', event);
}
if (responseJSON.code === 1900) { // session expired
this.setState({ showExpirationModal: true });
} else {
// TODO: consider removing handling of these errors locally
// Currently we'd be showing 2 popups in some places: one with a "permission denied", and another with this error handler
// alert('Unauthorized');
}
} else if (jqxhr.status === 500) { // TODO: see if we should to all 500 errors in this global handler
if (responseJSON.code === 8017) { // maintenance mode
alert(responseJSON.message);
}
} else if (!navigator.onLine) {
this.setState({ showConnectionModal: true });
} else if (responseJSON === undefined) {
console.error(event, jqxhr);
}
}
我不确定Fetch API是否支持这一点。来自OP上链接的文档 请注意,
fetch
规范不同于中的jQuery.ajax()
主要有两种方法需要记住:
- 从
fetch()
返回的承诺将不会在HTTP错误状态下拒绝
,即使响应是HTTP 404或500。相反,它会
正常解析(ok状态设置为false),仅
拒绝网络故障或任何阻止请求的情况
完成
要获取状态代码,请返回
jsiddle您可以尝试$。ajaxSetup
请更具体一些。看见和不,没有全局ajax错误处理程序(这是有充分理由的),所以,您要说的是,真正的问题是如何使用fetch检测和处理超时?为什么要包括所有这些关于jquery的各种各样的砖块和杂乱无章的内容,而不仅仅是问这个问题呢?获取响应。状态,响应。标题,响应为JSON
,文本,Blob
或数组缓冲
fetch("/path/to/server"/*, options object*/)
.then(response => ({headers: response.headers, code: response.status}))
.then(({headers, code}) => {
for (let [key, value] of headers) {
console.log(key, value)
}
console.log(code); // `403` at linked jsfiddle
// if (code === /* code */)
// do stuff
})
.catch(err => console.log(err));