Ad

Javascript Vanilla Ajax Turn Response Into Array Of Objects?

- 1 answer

I am trying to experiment with javascript on a deeper level. I am building my own $http object that has its own http methods.

var $http = {

    get: function(url, success, error) {
        httpHelper('GET', url, success, error);
    }

};

function httpHelper(type, url, success, error) {
    var xmlhttp;
    xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
            if(xmlhttp.status == 200){
                success(xmlhttp.responseText);
            }
            else if(xmlhttp.status == 400) {
                error(xmlhttp.status);
            }
            else {
                error(xmlhttp.status);
            }
        }
    }

    xmlhttp.open(type, url, true);
    xmlhttp.send();
};

On the server I am returning an array of JSON objects with the request.

app.get('/api/players/', function(req, res) {
  res.json([
    { name: 'Mike', points: 33 }, 
    { name: 'Shaq', points: 16 }
  ]);
});

On the client it seems I am getting a string [{"name":"Mike","points":33},{"name":"Shaq","points":16}].

How can I effectively convert the client side response to an array of JSON objects?

Ad

Answer

Just use JSON.parse

JSON.parse(xmlhttp.responseText);
Ad
source: stackoverflow.com
Ad