Ajax 如何在Vue属性中传递XMLHttpRequest responseText
我希望能够检索请求的响应并将其存储在属性中,但我无法在函数onreafystatchange中访问我的属性customerArrayAjax 如何在Vue属性中传递XMLHttpRequest responseText,ajax,vue.js,xmlhttprequest,Ajax,Vue.js,Xmlhttprequest,我希望能够检索请求的响应并将其存储在属性中,但我无法在函数onreafystatchange中访问我的属性customerArray export default { name: "CustomerList", data() { return { customerArray: [] } }, methods: { retrieve
export default {
name: "CustomerList",
data() {
return {
customerArray: []
}
},
methods: {
retrieveAllCustomer: function () {
var xhr = new XMLHttpRequest();
var url = "https://url";
xhr.open("GET", url, false);
xhr.onreadystatechange = function () {
if (this.readyState === XMLHttpRequest.DONE) {
if (this.status === 200) {
//Does not refer to customerArray
this.customerArray = JSON.parse(this.responseText);
} else {
console.log(this.status, this.statusText);
}
}
};
xhr.send();
}
}
}
是否可以指向onreadystatechange中的customerArray?
xhr.onreadystatechange=function()
会导致此
引用更改为XMLHttpRequest对象。因此,此.customerArray
不再存在。为了避免这种情况,请创建对原始this
的新引用:
retrieveAllCustomer: function () {
var comp = this;
var xhr = new XMLHttpRequest();
var url = "https://url";
xhr.open("GET", url, false);
xhr.onreadystatechange = function () {
if (this.readyState === XMLHttpRequest.DONE) {
if (this.status === 200) {
comp.customerArray = JSON.parse(this.responseText);
} else {
console.log(this.status, this.statusText);
}
}
};
xhr.send();
}
由于onreadystatechange之后的问题与之前的不同,因此您的问题是函数中的到期范围 使用
()=>{}
代替函数(){}
:
...
xhr.onreadystatechange = () => {
if (this.readyState === XMLHttpRequest.DONE) {
...
关于这一点,你可以读到很好的解释