gpt4 book ai didi

javascript - Ajax Javascript 类未定义

转载 作者:行者123 更新时间:2023-12-03 00:08:22 25 4
gpt4 key购买 nike

我是 Javascript 类(class)的初学者。我正在尝试设置一个非常简单的 ajax 类,但我陷入困境。这是我的代码:

class Ajax {
constructor() {
this.xhr = new XMLHttpRequest();
}

open(method, url, async) {
this.xhr.open(method, url, async);
this.xhr.send(null);
}

process() {
this.xhr.onreadystatechange = function() {
if(this.xhr.readyState == 4 && (this.xhr.status == 200 || this.xhr.status == 0)) {
alert(this.xhr.responseText);
}
}
}
}

const ajax = new Ajax();
ajax.open('GET', 'data.php?var1=hello&var2=world', true);
ajax.process();

我收到此错误

TypeError: this.xhr is undefined

指的是行:if(this.xhr.readyState == 4 ...

有人可以解释一下这里的 pb 是什么以及如何解决它吗?谢谢

最佳答案

您好,请尝试以下代码。

有引用。

class Ajax {
constructor() {
this.xhr = new XMLHttpRequest();
}

open(method, url, async) {
this.xhr.open(method, url, async);
this.xhr.send(null);
}

process() {
const xhrRef = this.xhr; // storing reference.

xhrRef.onreadystatechange = function() {
if(xhrRef.readyState == 4 && (xhrRef.status == 200 || xhrRef.status == 0)) {
alert(xhrRef.responseText);
}
}
}
}

const ajax = new Ajax();
ajax.open('GET', 'data.php?var1=hello&var2=world', true);
ajax.process();

没有引用

class Ajax {
constructor() {
this.xhr = new XMLHttpRequest();
}

open(method, url, async) {
this.xhr.open(method, url, async);
this.xhr.send(null);
}

process() {
this.xhr.onreadystatechange = function() {
if(this.readyState == 4 && (this.status == 200 || this.status == 0)) {
alert(this.responseText);
}
}
}
}

const ajax = new Ajax();
ajax.open('GET', 'http://dummy.restapiexample.com/api/v1/employees', true);
ajax.process();

关于javascript - Ajax Javascript 类未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54862287/

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