我正在尝试使用ajax检查给定的URL是否正常工作。所以我稍微修改了Ajax。
function isServerAlive()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4)
{
document.getElementById("myDiv").innerHTML=xmlhttp.status;
}
}
xmlhttp.open("GET","wrongurl",true);
xmlhttp.send();
}
我想要做的就是当网址错误时将xmlhttp.status显示为404或503。但它不是印刷品。有什么建议吗?
答案 0 :(得分:0)
.status
中有状态代码,.statusText
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState == 4)
console.log("Code: " + xmlhttp.status + "Status text: " + xmlhttp.statusText);
}
答案 1 :(得分:0)
将响应对象传递给xmlhttp事件,因此请改为使用:
xmlhttp.onreadystatechange=function(r) {
if (r.readyState == 4) {
document.getElementById("myDiv").innerHTML = r.status;
}
}
答案 2 :(得分:0)
我认为您无法使用XHR检查网址是否有效,因为网址必须来自the same origin作为原始网页。首先检查您的解决方案在访问本地URL时是否正常工作。