XMLHttpRequest ReadyState始终未定义 [英] XMLHttpRequest ReadyState always undefined

查看:139
本文介绍了XMLHttpRequest ReadyState始终未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在关注w3schools上的PHP/AJAX教程,并且在第一个方框遇到了一些障碍.每次我调用此函数时,readystate始终是未定义的.

I'm following the PHP/AJAX tutorials at w3schools, and I've hit a bit of a roadblock at square one. Every time I call this function, the readystate is always undefined.

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) { ...

然后它可以工作,但是在编写这样的代码时,感觉就像是魔术发生在这里".

Then it works, but it feels kind of like a "magic happens here" thing to be writing the code like this.

推荐答案

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

JS is case sensitive. You need to check the readyState property, not the readystate property.

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

这篇关于XMLHttpRequest ReadyState始终未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆