php - XMLHttpRequest ReadyState 始终未定义

标签 php javascript html ajax

我正在学习 w3schools 的 PHP/AJAX 教程,但在第一个方面遇到了一些障碍。每次调用此函数时,就绪状态始终未定义。

function showHint(str) {
    if (str.length == 0) {
        document.getElementById("txtHint").innerHTML = "";
            return;
        }

        var xmlhttp;

        if (window.XMLHttpRequest) {
            console.log("Using XMLHttpRequest");
            xmlhttp = new XMLHttpRequest();
        }
        else {
            console.log("Using ActiveXObject");
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }

        xmlhttp.open("GET", "gethint.php?q=" + str, true);
        xmlhttp.send();

        xmlhttp.onreadystatechange = function() {
        console.log(xmlhttp.readystate);

        if (xmlhttp.readystate == 4 && xmlhttp.status == 200) {
            console.log(xmlhttp.status);
            document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
        }
    }
}

如果我改变这一行:

if (xmlhttp.readystate == 4 && xmlhttp.status == 200) { ...

为此(通过打字错误):

if (xmlhttp.readystate = 4 && xmlhttp.status == 200) { ...

然后它就可以工作了,但是像这样编写代码感觉有点像“这里发生了魔法”。

最佳答案

JS 区分大小写。您需要检查 readyState 属性,而不是 readystate 属性。

    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        console.log(xmlhttp.status);
        document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
    }

关于php - XMLHttpRequest ReadyState 始终未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13636612/

相关文章:

html - HTML5 中的自闭合标签(void 元素)

javascript - 我想统计用户参与了多少问题

php - 设置 var mysql 并启动事务

javascript - 如何从对象数组中提取多属性重复项?

javascript - Google GeoChart 国家

javascript - 悬停标题以显示文本

php - 如何在php中添加用户角色

php - CodeIgniter 网站上的错误 "too many connections"

javascript - 当我从下拉列表中选择选项时,按钮应该会自动触发并生成唯一的 ID

Javascript 捕获未选择的单选按钮以及文本框和警报