2010-08-30 142 views
2

現在我努力獲得這個簡單的PHP AJAX請求來工作。簡單的PHP,AJAX請求

<html> 
    <head> 
     <script type="text/javascript"> 
     function getSuggestions(type){ 
      if(type == "") 
      { 
      document.getElementById("entries").innerHTML="test" 
      return; 
      } 
      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("entries").innerHTML=xmlHttp.response; 
      } 
      } 
      xmlHttp.open("GET","getData.php?status="+type,true); 
      xmlHttp.send(); 
     } 
     </script> 
    </head> 
    <body> 
    <div id="A" onclick='getSuggestions("A")'>Click for A</div> 
    <div id="P" onclick='getSuggestions("P")'>Click for P</div> 
    <div id="R" onclick='getSuggestions("R")'>Click for R</div> 
    <div id="entries"></div> 
    </body> 
    </html> 

下面是訪問getdata.php

<?php 
    $status = $_GET["status"]; 
    echo $status; 
?> 

每次我點擊任何我在「項」標籤獲取「不確定」的標籤。有誰能解釋爲什麼它是未定義的嗎?

回答

5

使用xmlHttp.responseText

+1

+1 @akellehe - Danget ...打我給它= P – 2010-08-30 20:36:40

+0

哈哈哈,:)謝謝 – KeatsKelleher 2010-08-30 20:38:12

+0

哇無法相信我錯過了:P,謝謝 – Albinoswordfish 2010-08-30 20:40:50

3

這就是我如何處理AJAX。從本質上講akellehe的回答的一個例子

function getSuggestions(type){ 
    if(type == "") { 
     document.getElementById("entries").innerHTML="test" 
     return; 
    } 

    var r = getXmlObject(); 
    var url= "getData.php?status="+type; 

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

     r.open("POST", url, true); 

     r.onreadystatechange = function(){ 
      if (r.readyState == 4) { 
       document.getElementById("entries").innerHTML= r.responseText; 
      } 
     }; 

     r.send(null); 

    } 
} 

//////////////////////////////////// 
function getXmlObject() { 
    if (window.XMLHttpRequest) { 
     return new XMLHttpRequest(); 
    } else if(window.ActiveXObject) { 
     return new ActiveXObject("Microsoft.XMLHTTP"); 
    } else { 
     alert('Status: Cound not create XmlHttpRequest Object. Consider upgrading your browser.'); 
    } 
} 
+0

放哪兒receiveReq從哪裏來? – Albinoswordfish 2010-08-30 20:57:00

+0

哎呀。複製粘貼錯誤.. receiveReq應該是「r」 - 在後期修復。 – Dutchie432 2010-08-30 20:58:16