2012-06-17 100 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