XMLHttpRequest 失败如何处理?
How to handle when XMLHttpRequest fails?
我正在尝试进行 XHR 调用,但如果服务器不在线或者如果在调用发起后互联网断开连接,那么我会失败,因为状态
Network Log Screenshot
我尝试了 onload()、onerror()、onreadystatechange() 事件,但 none 事件被触发了。
这是我的 Javascript 片段
function login() {
animateLogo(true);
document.getElementsByTagName('fieldset')[0].setAttribute('disabled', 'true');
var http = new XMLHttpRequest();
var url = "localhost:3000/login";
var params = `email=${email}&password=${password}&remember=${remember}`;
http.open('POST', url, true);
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
http.onload = function () {
animateLogo(false);
// Response handler
}
http.send(params); }
由于 none 个事件被触发,我无法停止我的动画
您可以检查请求的状态
(成功 = 200,未找到 = 404,服务器错误 = 500 等。)
const http = new XMLHttpRequest();
const url = "localhost:3000/login";
http.open('POST', url, true);
const params = `email=${email}&password=${password}&remember=${remember}`;
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
http.onreadystatechange = function() {//Call a function when the state changes.
if(this.readyState == XMLHttpRequest.DONE && this.status == 200) {
// Request finished. Do processing here.
}
// handle other status here
}
http.send(params);
我正在尝试进行 XHR 调用,但如果服务器不在线或者如果在调用发起后互联网断开连接,那么我会失败,因为状态 Network Log Screenshot
我尝试了 onload()、onerror()、onreadystatechange() 事件,但 none 事件被触发了。 这是我的 Javascript 片段
function login() {
animateLogo(true);
document.getElementsByTagName('fieldset')[0].setAttribute('disabled', 'true');
var http = new XMLHttpRequest();
var url = "localhost:3000/login";
var params = `email=${email}&password=${password}&remember=${remember}`;
http.open('POST', url, true);
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
http.onload = function () {
animateLogo(false);
// Response handler
}
http.send(params); }
由于 none 个事件被触发,我无法停止我的动画
您可以检查请求的状态 (成功 = 200,未找到 = 404,服务器错误 = 500 等。)
const http = new XMLHttpRequest();
const url = "localhost:3000/login";
http.open('POST', url, true);
const params = `email=${email}&password=${password}&remember=${remember}`;
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
http.onreadystatechange = function() {//Call a function when the state changes.
if(this.readyState == XMLHttpRequest.DONE && this.status == 200) {
// Request finished. Do processing here.
}
// handle other status here
}
http.send(params);