请求完成之前,您正在查看xhr.status。仅在status为readyState时检查4:
var xhr = new XMLHttpRequest();
xhr.addEventListener("readystatechange", processRequest, false);
function processRequest(e) {
if (xhr.readyState == 4) {
if (xhr.status >= 200 && xhr.status < 300) {
// All good
console.log(xhr.status);
}
else {
// Something went wrong
alert(xhr.status);
}
}
}
xhr.open('GET', "http://localhost:8080/hello", true);
xhr.send();
也就是说,在所有主流浏览器上,XMLHttpRequest已过时。而是使用fetch:
fetch("http://localhost:8080/hello")
.then(response => {
if (!response.ok) {
throw new Error(response.status);
}
})
.then(response => {
// Read the body of the response
return response.text(); // or .json(), .arrayBuffer(), .blob(), .formData()
})
.then(data => {
// All good, use the data
})
.catch(error => {
// Handle the error
});
如果愿意,可以使用.text(它是ReadableStream)代替.json,response.body等助手。
您说过,更新后的代码仍处于0状态。我能看到的唯一方法是,如果您正在发出跨域请求,并且受到Same Origin Policy的阻止。您应该在Web控制台中得到一个非常明确的错误。如果是这种情况,请查看CORS(如果您控制另一端)或JSONP或使用服务器为您发出请求。那里有很多有关SOP和CORS的信息。