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

标签 javascript 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;

注意删除的括号。

关于javascript - onreadystatechange 函数在 AJAX 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19463278/

相关文章:

javascript - 动态左边距

javascript - jQuery UI 对话框在 Enter KeyPress 上更改 URL

javascript - JS 递归过多

javascript - Firebase + REST + jquery 产生奇怪的键

php - 如何使用 "favorite"按钮的 php/mysql 将 POST jquery ajax 调用发送到服务器?

javascript - XML 请求的多数组

javascript - 如何构建 mongoDB 查询来查找文档字段中的任何 myArray id?

javascript - 使用 laravel 响应 ajax 和验证响应

javascript - 在 Derived.prototype = new Base 处使用 'new' 关键字的原因是什么

php - 检查地址栏并使用 javascript 重定向