2013-06-20 37 views
0

如果我有一個從遠程服務器調用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> 
+3

http://en.wikipedia.org/wiki/Same_origin_policy –

+0

你爲什麼標記「jQuery的」當你不使用jquery ? 在jQuery中,您可以使用jsonp數據類型進行跨域請求。 回調「失敗」有3個參數。有一個你可以得到http狀態(503服務不可用)。 – PKeidel

回答

3

你可以檢測到不同的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'); 
    } 
} 
+0

cfs這工作正常,但不是警報如何顯示頁面上的消息?是document.write? – user2430338

+0

沒關係。 document.write作品。再次感謝。 – user2430338

+0

@ user2430338很高興我可以幫助:)歡迎來到StackOverflow!如果它能幫助你解決問題,那麼在這裏鼓勵你接受並讚揚一個答案,這樣其他具有相同問題的人就能找到答案。謝謝,祝你好運! – cfs