2014-02-07 27 views
-1
// JavaScript Document 
var xmlHttp = createXmlHttpRequestObject(); 

function createXmlHttpRequestObject(){ 
    var xmlHttp; 

    if(window.ActiveXObject){ 
     try{ 
      xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); 

     } 
     catch(e){ 
      xmlHttp=false; 
     } 
    } 
    else{ 
     try{ 
      xmlHttp=new XMLHttpRequest(); 

     } 
     catch(e){ 
      xmlHttp=false; 
     } 
    } 
    if(!xmlHttp){ 
     alert('cant create the object'); 
    } 
    else{ 

     return xmlHttp; 
    } 
} 

function process(){ 

    if(xmlHttp.readyState==4 || xmlHttp.readyState==0){ 

     food=encodeURIComponent(document.getElementById("userinput").value); 
     xmlHttp.open("GET","foodstore.php?food="+food,true); 
     xmlHttp.onreadystatechange=handleServerResponse; 
     xmlHttp.send(null); 
    } 
    else{ 
       setTimeout(process(),1000); 
    } 
} 

function handleServerResponse(){ 

    if(xmlHttp.readyState==4){ 
     if(xmlHttp.status==200){ 

      xmlResponse = xmlHttp.responseXML; 
      xmlDocumentElement =xmlResponse.documentElement; 
      message=xml.DocumentElement.firstChild.data; 
      document.getElementById("underinput").innerHTML=message; 
      setTimeout(process(),1000); 
     } 
     else{ 

      alert('something went wrong'); 
     } 
    } 
    else{ 
     alert('something went wrong 2'); 
    } 
} 

在上面的代碼中,我xmlHttp.readyState==4不執行,而執行在else警報每次。AJAX xmlHttp.readyState == 4不執行

+0

你是如何調用open(),送(),onreadystatechange的?表明 – epascarello

回答

0

首先這是錯誤的

setTimeout(process(),1000); 

您將要作出一個無限循環,再加上它是沒有意義的,你爲什麼會這麼做。您正在調用該函數,而不是爲其分配參考。

setTimeout(process,1000); 

其次,readystate可以是0,1,2,3,4,這不是您的警報狀態的錯誤。


更改你的代碼

function handleServerResponse() { 
    if(xmlHttp.readyState==4){ 
     if(xmlHttp.status==200){ 
      var xmlResponse = xmlHttp.responseXML; 
      var xmlDocumentElement =xmlResponse.documentElement; 
      var message=xml.DocumentElement.firstChild.data; 
      document.getElementById("underinput").innerHTML=message; 
      setTimeout(process,1000); 
     } 
     else{ 
      alert('something went wrong.\n' + xmlHttp.status + "\n" + xmlHttp.statusText); 
     } 
    } 
} 


function process(){ 
    var food=encodeURIComponent(document.getElementById("userinput").value); 
    xmlHttp = createXmlHttpRequestObject(); 
    xmlHttp.open("GET","foodstore.php?food="+food,true); 
    xmlHttp.onreadystatechange=handleServerResponse; 
    xmlHttp.send(null); 
} 
+0

就緒狀態的變化是不是一個錯誤,但我只是印製的消息,以確保我的,如果不工作..... – user3282599

+0

每次我運行一個程序正在打印警報在別人,而不是布萊恩如果statment – user3282599

+0

見我編輯上面 – epascarello

0

的setTimeout(過程(),1000); setTimeout的用法不正確。 嘗試setTimeout('process()',1000);或setTimeout(進程,1000);

0

在功能handleserver響應,它是顯示否則將對應於if(xmlHttp.readyState==4)聲明。

我XAMPP服務器上運行我的程序。我做對了嗎?

0

舉行的XMLHttpRequest的狀態。從0到4的變化: 0:請求未初始化 1:服務器連接建立 2:請求接收 3:處理請求 4:請求完成和響應準備

這些準備狀態改變的值,所以根據這個要麼我的要求沒有完成或我的反應沒有準備好。

我已刪除了setTimeout(process, 1000),它仍然不能正常工作