2012-06-17 98 views
0

我試圖通過點擊一個按鈕來運行PHP代碼,但它似乎不工作。我在MAPM服務器上運行它。PHP代碼不運行

<html> 
    <head> 
    </head> 
    <div onClick="count();">Click!</div> 
    <script> 
function count() { 
    var xhr; 
    if (window.XMLHttpRequest) { 
     xhr = new XMLHttpRequest(); 
    } else { 
     xhr = new ActiveXObject("Microsoft.XMLHTTP"); 
    } 
    xhr.open('GET', 'count.php'); 
    xhr.send(); 
}​ 
    </script> 

    </body> 
</html> 

在PHP文件(count.php),我們有這樣的代碼:

<?php 
Print "Hello, World!"; 
?> 
+0

URL是否正確?或將它是「/count.php」? – Arnab

+3

你的意思是「似乎沒有工作」?該腳本沒有副作用,並且您沒有對輸出做任何事情,所以即使請求成功,也不會發生任何事情。這是真實的代碼嗎? –

+0

這是真實的代碼 – user1431627

回答

2

你需要你的網頁聽請求;

function count() { 
    var xhr; 
    if (window.XMLHttpRequest) { 
     xhr = new XMLHttpRequest(); 
    } else { 
     xhr = new ActiveXObject("Microsoft.XMLHTTP"); 
    } 
    xhr.onreadystatechange =  function(){ 
    if(xhr.readyState == 4){ 
     if(xhr.status == 200){ 
      // WHAT HAPPENS ON SUCCESS 
      alert(xhr.responseText); 
     }else{ 
       alert('timeout error or something'); 
     } 
     } 
    }; 
    xhr.open('GET', 'count.php'); 
    xhr.send(); 
}​; 
+0

爲什麼選擇這項工作? – user1431627

0

你需要傳遞nullsend()方法如下圖所示(也可以肯定的是,網址是正確的,我的直覺是,它應該是「/count.php」):

xhr.send(null) // it's a GET request 

有關詳細教程,請查看此MDN文檔https://developer.mozilla.org/en/AJAX/Getting_Started

+0

不過,這個劑量不起作用。 – user1431627

+0

將「true」作爲第三個參數傳遞給你的'xhr.open()'調用,就像'xhr.open('GET','/count.php',true);' – Arnab

+0

http://pastebin.com/AvMMNusw - 像這樣?這個劑量不起作用。 – user1431627