Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ajax/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ajax 如何在Vue属性中传递XMLHttpRequest responseText_Ajax_Vue.js_Xmlhttprequest - Fatal编程技术网

Ajax 如何在Vue属性中传递XMLHttpRequest responseText

Ajax 如何在Vue属性中传递XMLHttpRequest responseText,ajax,vue.js,xmlhttprequest,Ajax,Vue.js,Xmlhttprequest,我希望能够检索请求的响应并将其存储在属性中,但我无法在函数onreafystatchange中访问我的属性customerArray export default { name: "CustomerList", data() { return { customerArray: [] } }, methods: { retrieve

我希望能够检索请求的响应并将其存储在属性中,但我无法在函数onreafystatchange中访问我的属性customerArray

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) {
...
关于这一点,你可以读到很好的解释