olo*_*ore 23 javascript browser xmlhttprequest
当我的页面通过XHR加载内容时,如果用户单击停止按钮或单击转到另一个页面,则会调用XHR error()函数.除了在页面上看到大量(红色)错误消息的用户震惊之外,这通常不是什么大问题.
消息是有效的 - 检索内容确实有错误 - 但这是由于用户交互,而不是因为系统故障.
有没有办法区分(404 | 500 |超时错误)和用户点击浏览器的停止按钮导致的错误?
编辑:我正在使用Dojo(因此错误函数引用),但我相信这将是任何XHR实现中常见的情况.调用error()时,我将查看xhr对象的readyState
CMS*_*CMS 39
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);
}
});
};
Run Code Online (Sandbox Code Playgroud)
一个简单的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);
}
Run Code Online (Sandbox Code Playgroud)
在此处运行上述代码段.