你能从xhttp请求中返回一个值吗?

时间:2017-04-29 11:12:48

标签: javascript xmlhttprequest vue.js

我有一个xhttp函数调用我的db并返回一个数组,该数组根据调用时在xhttp函数中传递的参数而有所不同。 这是我的xhttp函数:

fetchGroupInfo: function (groupNum) {
                var global = this;

                var xhttp = new XMLHttpRequest();
                xhttp.onreadystatechange = function() {                                                         //(callback function)this function runs after xhttp.open because we have asynchronous data sending so as soon as the data is recieved this is run
                    if (xhttp.readyState === XMLHttpRequest.DONE && xhttp.status == 200) {
                        console.log(this.responseText);
                        //I parse the rawdata received into jason structure then I pass it into and call the manipulate function
                        var rawdata = this.responseText;
                        var json = JSON.parse(rawdata); //parses the query result
                        return json;
                    }
                };

                xhttp.open("GET", "http://178.62.***.***:1020/groupInfo/"+groupNum, true);
                xhttp.send();
            },

因为我需要在页面加载时调用该函数8次并返回8个不同的数组,所以我不想为每个需要返回的不同数组写出8次这个函数。我希望以后可以做的是这样的,这样我就可以保持我的代码清洁:

this.group1Info = this.fetchGroupInfo(1);
this.group2Info = this.fetchGroupInfo(2);
this.group3Info = this.fetchGroupInfo(3);
this.group4Info = this.fetchGroupInfo(4);
.....

目前设置函数的方式是返回一个未定义的值,我将如何使其工作?

1 个答案:

答案 0 :(得分:0)

您的代码是异步的,因此您可以添加回调函数,然后在回调中设置变量:

fetchGroupInfo: function (groupNum, callback) {
            var global = this;

            var xhttp = new XMLHttpRequest();
            xhttp.onreadystatechange = function() {                                                         //(callback function)this function runs after xhttp.open because we have asynchronous data sending so as soon as the data is recieved this is run
                if (xhttp.readyState === XMLHttpRequest.DONE && xhttp.status == 200) {
                    console.log(this.responseText);
                    //I parse the rawdata received into jason structure then I pass it into and call the manipulate function
                    var rawdata = this.responseText;
                    var json = JSON.parse(rawdata); //parses the query result
                    return callback(json);
                }
            };

            xhttp.open("GET", "http://178.62.***.***:1020/groupInfo/"+groupNum, true);
            xhttp.send();
        }

现在要设置变量,每次调用fetchGroupInfo时都会传递回调:

this.fetchGroupInfo(1, function(result) {
  this.group1Info = result;
});