微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – onreadystatechange函数在AJAX中不起作用

XMLHttpRequest()对象而言,它很好,问题在于onreadystatechange,例如,如果我以这种方式放置代码,它就完美了.

function process(){
    var xmlHttp = new XMLHttpRequest();

    if(xmlHttp){
        xmlHttp.onreadystatechange = function(){
            theD = document.getElementById("theD");
            if(xmlHttp.readyState == 1){
                theD.innerHTML += "Status 1: Server connection established ! <br/>";
                }
            else if(xmlHttp.readyState == 2){
                theD.innerHTML += "Status 2: Request recieved ! <br/>";
                }
            else if(xmlHttp.readyState == 3){
                theD.innerHTML += "Status 3: Processing Request ! <br/>";
                }
            else if(xmlHttp.readyState == 4){

                if(xmlHttp.status == 200){
                    var text = xmlHttp.responseText;
                    theD.innerHTML += "Status 4: Processing Request ! <br/>";
                    theD.innerHTML += text;
                    }
                else{
                    alert("Something is wrong !");
                    }
                }
            };
        xmlHttp.open("GET", "hello.txt", true);
            xmlHttp.send();
        }
}

但如果我创建handleServerResponse()的函数

function handleServerResponse(){
    theD = document.getElementById("theD");
            if(xmlHttp.readyState == 1){
                theD.innerHTML += "Status 1: Server connection established ! <br/>";
                }
            else if(xmlHttp.readyState == 2){
                theD.innerHTML += "Status 2: Request recieved ! <br/>";
                }
            else if(xmlHttp.readyState == 3){
                theD.innerHTML += "Status 3: Processing Request ! <br/>";
                }
            else if(xmlHttp.readyState == 4){

                if(xmlHttp.status == 200){
                    var text = xmlHttp.responseText;
                    theD.innerHTML += "Status 4: Processing Request ! <br/>";
                    theD.innerHTML += text;
                    }
                else{
                    alert("Something is wrong !");
                    }

                }
}

并称之为

xmlHttp.onreadystatechange = handleServerResponse();

它不起作用.如果我错了,请指出.

解决方法:

尝试使用

xmlHttp.onreadystatechange = handleServerResponse;

请注意删除的paranthesis.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐