我正在尝试使用以下代码来处理AJAX错误,但无法正常工作
function ajaxPost(url, data, success, error) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status === 200) {
if (typeof success === "function") {
success(xmlhttp.responseText);
}
}else if([404, 500 , 503, 504 ].indexOf(xmlhttp.status) > -1){
if(typeof error === "function"){
error();
}
}
}
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
xmlhttp.send(JSON.stringify(data));
}
我是否还缺少任何其他状态代码[404, 500 , 503, 504 ]
?我并没有重新发明轮子,我已经使用本机JavaScript编写了整个DOM,并且不想仅为AJAX包含80KB文件。请帮我。
上面的函数已成功将数据发布到服务器,但是在服务器不可用时未能引发错误。请帮我解决这个问题。
// try this code
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4) {
var resp=eval('('+xmlhttp.responseText+')');
if( xmlhttp.status == 200 ) {
// success
} else if( xmlhttp.status >= 500 ) {
// internal server error
} else if ( xmlhttp.status >= 402 && xmlhttp.status <= 420 ) {
// error
} else if( xmlhttp.status == 400 || xmlhttp.status == 401 ) {
// bad request & unauthorized error
}
}
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句