2012-07-28 124 views
-1

我想点击按钮触发AJAX请求,但我无法在后端触发它。使用PHP的AJAX请求

的index.php

<html> 
    <head> 
     <script type="text/javascript"> 
      var req = new XMLHttpRequest(); 
      function send1() 
      { 
       req.open("GET", "process.php?q=hello", true); 
       req.send();   
       alert(req.responseText);  
      } 
     </script> 
    </head>  

    <button onclick=send1()>send</button> 

</html> 

process.php

<?php 
$new= $_GET['q']; 
echo $new; 
?> 

这应该给我 “你好” 在alertbox为什么它是不是?

+2

学习jQuery,它会让你的生活更简单! – Sourav 2012-07-28 16:47:35

+0

@Sourav:我同意,但对于以前从未使用过AJAX的人来说,我认为在将它抽象出来之前,看看它是如何在jQuery的“底层”下工作是非常有益的。 – 2012-07-28 16:48:13

+0

@Sourav:我不同意。学习Javascript,然后学习ajax如何工作,然后*学习jquery(或其他库)。有太多的人把这整件事情想成一串魔法咒语,不知道里面发生了什么。 – 2012-07-28 16:52:11

回答

7

AJAX中的第一个A表示“异步”。你需要做的是听readyState改变:

req.open(...); 
req.onreadystatechange = function() { 
    if(this.readyState == 4) { 
     if(this.status == 200) alert(this.responseText); 
     else alert("HTTP error "+this.status+" "+this.statusText); 
    } 
}; 
req.send();