我正在使用后面的代码来检索就绪状态,这对我来说很有用。请问如何在此内容中添加 else 语句。就像如果 url 不可用我想向用户打印一条消息。喜欢
document.getElementById("div p").innerHTML = "Ping is not success!";
并尝试让它看起来比纯 html 文本更漂亮一点。 她是我的代码:
url = "<whatever you want to ping>"
ping = new XMLHttpRequest();
ping.onreadystatechange = function(){
document.body.innerHTML += "</br>" + ping.readyState;
if(ping.readyState == 4){
if(ping.status == 200){
result = ping.getAllResponseHeaders();
document.body.innerHTML += "</br>" + result + "</br>";
}
}
}
ping.open("GET", url, true);
ping.send();
最佳答案
当请求结束时,readyState
为4
,但status
可能是200
以外的值>。如果 status
为 0
,则表示网络错误或 CORS 故障(对于跨源服务器)。如果它是其他值(例如 404
),则意味着脚本已到达服务器,但服务器未成功处理请求(要么因为使用的 URL 路径没有意义,要么因为服务器端发生错误等)
ping.onreadystatechange = function(){
document.body.innerHTML += "<br>" + ping.readyState;
if(ping.readyState == 4){
if(ping.status == 200){
result = ping.getAllResponseHeaders();
document.body.innerHTML += "<br>" + result + "<br>";
} else if(ping.status == 0) {
document.getElementById("foobar").innerHTML = "Ping is not successful! Could not get any response from the server, due to a network failure, CORS error, or offline server.";
} else {
result = ping.getAllResponseHeaders();
document.getElementById("foobar").innerHTML = "We got a response from the server, but it was status code " + ping.status;
}
}
}
关于javascript - 使用 AJAX,并检索就绪状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40534080/