2010-12-15 85 views
4

我寫了如下的Ajax函數。Ajax函數調用

它無法正常工作。如果我刪除xmlhttp.status==400那麼它正在工作。我在這個例子中犯了什麼錯誤?

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
    <head> 
     <title> New Document </title> 
     <script type="text/javascript"> 
      function getAjax() 
      { 
       if (window.XMLHTTPRequest) 
       { 
        xmlhttp=new XMLHTTPRequest(); 
       } 
       else 
       { 
        xmlhttp=new ActiveXObject("Microsoft.xmlHTTP"); 
       } 
       xmlhttp.onreadystatechange=function() 
       { 
        if (xmlhttp.readyState==4 && xmlhttp.status==400) 
        { 
         document.getElementById('mydiv').innerHTML=xmlhttp.responseText; 
        } 
       } 
       xmlhttp.open("GET","testajax.txt",true); 
       xmlhttp.send(null); 
      } 
     </script> 
    </head> 

    <body> 
     <input type="button" value="Get content" onclick="getAjax()"><br> 
     <div id="mydiv"></div> 
    </body> 
</html> 

回答

1

「另一個簡單的使用如果URL存在HTTP有雙方HEAD返回不同的狀態碼和GET請求尋找, , 200表示成功,404代表失敗,和其他人的意思是其他的東西。 請參閱HTTP status codes以獲取完整說明。「

使用XMLHTTP對象的狀態屬性爲您提供此狀態

  if (xmlhttp.readyState==4) { 
      if (xmlhttp.status==200) alert("URL Exists!") 
      else if (xmlhttp.status==404) alert("URL doesn't exist!") 

      } 

http://www.jibbering.com/2002/4/httprequest.2004.9.html

0

正確的 「if」 的條件應該是: -

if (xmlhttp.readyState == 4 && xmlhttp.status == 200) 
{ 
    document.getElementById('mydiv').innerHTML=xmlhttp.responseText;    
} 

更多更深入的瞭解,你可以看到從IBM技術庫的Mastering AJAX這個漂亮&詳細的文章。此外,您可以輕鬆使用jQuery庫的jQuery.ajax() API。

希望它有幫助。

+0

與xmlhttp.status == 200還沒有給出來放..先生 – Mihir 2010-12-15 05:42:59

+0

@Mihir - 如果儘可能使用jQuery AJAX API。這是最好的一個沒有什麼細節要求。 – 2010-12-15 05:46:55