如果我有一个从远程服务器调用 php 文件的代码,但该 php 文件不可用,如何以及在哪里添加消息“服务器不可用”?这是我的代码:
<html>
<head>
<script language="Javascript">
function View(){
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 && xmlhttp.status==200)
{
document.getElementById("datatable").innerHTML=xmlhttp.responseText;
}
xmlhttp.open("POST", "http://someremoteserver/somephpfile.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send();
}
</script>
</head>
<body onload="View();" >
<div id="datatable" align="center"></div>
</body>
</html>
最佳答案
您可以检测到不同的 HTTP Status codes并根据响应做一些事情。或者,如果状态不是 200,您可以只实现一个通用处理程序:
if (xmlhttp.readyState==4) {
if (xmlhttp.status==200) {
document.getElementById("datatable").innerHTML=xmlhttp.responseText;
} else if (xmlhttp.status == 503) { //specific error code
alert('Sorry, this server is unavailable');
} else { //generic error handler
alert('There was an error with your request');
}
}
关于javascript - 服务器不可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17222406/