[Vuejs]-Can you return a value from a xhttp request?

0👍

Your code is asynchronous, so you’ll you to add a callback function and then set your variables in the callback:

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();
        }

and now to set the variables, pass a callback each time you call fetchGroupInfo:

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

Leave a comment