gpt4 book ai didi

javascript - AJAX 中 HTTP 对象的更简洁语法?

转载 作者:行者123 更新时间:2023-11-30 12:56:48 26 4
gpt4 key购买 nike

这里是 AJAX 新手...所以下面这段代码对我有用,它在 onclick 事件期间被调用:

function updateText() {
var http = getHTTPObject();
http.open("GET","ajax_info.asp",true);
http.onreadystatechange = function() {
if (http.readyState == 4) {
document.getElementById("myDiv").innerHTML=http.responseText;
}
}
http.send();
}

但是,当我尝试像下面那样清理它时,它不再起作用了。下面的代码不是正确的回调语法吗?

function handleHTTPResponse() {
if (http.readyState == 4) {
document.getElementById("myDiv").innerHTML=http.responseText;
}
}

function updateText() {
var http = getHTTPObject();
http.open("GET","ajax_info.asp",true);
http.onreadystatechange = handleHTTPResponse;
http.send();
}

最佳答案

函数 handleHTTPResponse() 不知道 http 变量是什么。在其范围内没有使用该名称声明的变量。

将其作为参数传入

function handleHTTPResponse(http) {
if (http.readyState == 4) {
document.getElementById("myDiv").innerHTML=http.responseText;
}
}

...

http.onreadystatechange = function() { handleHTTPResponse(http) };

或者,正如@dc5 在另一个答案中指出的那样,使用 this

http.onreadystatechange = function() { handleHTTPResponse(this) };

或等价地更干净

function handleHTTPResponse() {
if (this.readyState == 4) {
document.getElementById("myDiv").innerHTML=this.responseText;
}
}

...

http.onreadystatechange = handleHTTPResponse;

或者,将函数放在范围内,以便它可以“看到”http

function updateText() {

function handleHTTPResponse() {
if (http.readyState == 4) {
document.getElementById("myDiv").innerHTML=http.responseText;
}
}

var http = getHTTPObject();
http.open("GET","ajax_info.asp",true);
http.onreadystatechange = handleHTTPResponse;
http.send();
}

或者,使 http 全局

var http;    

function handleHTTPResponse() {
if (http.readyState == 4) {
document.getElementById("myDiv").innerHTML=http.responseText;
}
}

function updateText() {
http = getHTTPObject();
http.open("GET","ajax_info.asp",true);
http.onreadystatechange = handleHTTPResponse;
http.send();
}

关于javascript - AJAX 中 HTTP 对象的更简洁语法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18807131/

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