";找不到元素";试图让AJAX向PHP发送/接收字符串


"No Element Found" trying to make AJAX send / receive string to PHP

我阅读了W3Schools上的AJAX教程,做了一个基本相同的简单示例,但它产生了一个错误。如果好奇的话,教程就在这里:http://www.w3schools.com/ajax/ajax_aspphp.asp

我想向PHP文件发送一个字符串(类似于链接中的第三个代码块(,但我收到了一个错误:">未找到任何元素"。Firefox突出显示了PHP文件的第5行,它只是?>

带有AJAX代码的文件名为"getHello.html"(.html正确吗?(,代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>AJAX Hello World Example</title>
    <script>
        function sayHello(str) {
            if (str.length == 0) {
                document.getElementById("showText").innerHTML = "Hello World!";
                return;
            }
            var xmlHttp = new XMLHttpRequest();
            xmlHttp.onreadystatechange = function() {
                if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
                    document.getElementById("showText").innerHTML = xmlHttp.responseText;
                }
            }
            xmlHttp.open("GET", "sendHello.php?q="+str, true);
            xmlHttp.send();
        }
    </script>
</head>
<body>
    <input type="text" id="textIn" onkeyup="sayHello(this.value);"/><br/><br/>
    <div id="showText"></div>
</body>
</html>

PHP文件名为"sendHello.PHP",代码为:

<?php
    $q = $_GET["q"];
    $response = "Hello World! Sent: ".$q;
    echo $response;
?>

使用本地服务器和HTML编辑器,当您忘记通过文件运行HTML时,可以(在错误控制台上(得到此错误:protocol

你的示例代码对我来说很好。刷新页面,如果你在你控制的服务器上运行,但仍然不起作用,也可以重新启动服务器(你永远不会知道,也许你打开了某种服务器端缓存(。是的,.html是getHello.html的正确扩展,因为它不包含任何PHP代码。