gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:02:57 26 4
gpt4 key购买 nike

就 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com