我正在使用后面的代码来检索就绪状态,这对我有用。我可以请问如何在此内容中添加其他政治家。如果网址不可用,我想向用户打印一条消息。像
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();
答案 0 :(得分:1)
请求结束时,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;
}
}
}