简单的PHP,AJAX请求

时间:2010-08-30 20:27:40

标签: php html 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;
?>

每当我点击任何标签时,我会在“entries”标签中获得“undefined”。有人可以解释为什么它没有定义吗?

2 个答案:

答案 0 :(得分:5)

使用xmlHttp.responseText

答案 1 :(得分: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.');
    }
}