PHP 代码无法运行

PHP code does not run

本文关键字:运行 代码 PHP      更新时间:2023-09-26

我正在尝试通过单击按钮来运行PHP代码,但它似乎不起作用。我正在 MAPM 服务器上运行它。

<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!";
?>

你需要你的页面来监听请求;

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();
}​;

您需要将null传递给如下所示的send()方法(还要确保URL是正确的,我的预感是它应该是"/count.php"):

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

有关详细教程,请查看此 MDN 文档 https://developer.mozilla.org/en/AJAX/Getting_Started