2012-07-28 122 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();