当我的页面通过 XHR 加载内容时,如果用户单击停止按钮或单击转到另一个页面,则会调用 XHR error() 函数。除了用户在页面上看到大量(红色)错误消息而感到震惊之外,这通常不会是什么大问题。
消息有效 - 检索内容时确实出现错误 - 但这是由于用户交互造成的,而不是由于系统故障。
有没有办法区分(404 | 500 | 超时错误)和用户点击浏览器停止按钮导致的错误?
编辑:我正在使用 Dojo(因此是错误函数引用),但我相信这将是任何 XHR 实现中常见的情况。当 error() 被调用时,我将查看 xhr 对象的 readyState
最佳答案
区分 HTTP 错误(404
、401
、403
、500
等)和请求中止错误(即用户按了 Esc 键或导航到其他页面),您可以检查 XHR.status 属性,如果请求已中止,则状态成员将为零:
document.getElementById('element').onclick = function () {
postRequest ('test/', null, function (response) { // success callback
alert('Response: ' + response);
}, function (xhr, status) { // error callback
switch(status) {
case 404:
alert('File not found');
break;
case 500:
alert('Server error');
break;
case 0:
alert('Request aborted');
break;
default:
alert('Unknown error ' + status);
}
});
};
一个简单的 postRequest 函数:
function postRequest (url, params, success, error) {
var xhr = XMLHttpRequest ? new XMLHttpRequest() :
new ActiveXObject("Microsoft.XMLHTTP");
xhr.open("POST", url, true);
xhr.onreadystatechange = function(){
if ( xhr.readyState == 4 ) {
if ( xhr.status == 200 ) {
success(xhr.responseText);
} else {
error(xhr, xhr.status);
}
}
};
xhr.onerror = function () {
error(xhr, xhr.status);
};
xhr.send(params);
}
运行上面的代码片段here .
关于javascript - 检测 XHR 错误确实是由于浏览器停止或点击新页面造成的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1442425/