Чтобы различать ошибки 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);
}
Запустите приведенный выше фрагмент здесь .