Michael Joseph Aubry
Michael Joseph Aubry

Reputation: 13402

Javascript vanilla ajax turn response into array of objects?

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?

Upvotes: 0

Views: 1370

Answers (2)

Clavin
Clavin

Reputation: 1190

Even though a comment has already answered the question, I felt I may as well throw out an actual answer (plus clarification on where to put it!)

You're looking for JSON.parse. Where you put it depends on if your $http object will only be getting JSON responses or not. If it does, then put your JSON.parse in what you send to success:

success(JSON.parse(xmlhttp.responseText));

However, if you also want to accept other types of requests, then put your JSON.parse in your callback that is success.

$http.get('some url', function(result) {
    result = JSON.parse(result);
}, function() {
    // ...
});

Upvotes: 2

Marcos Casagrande
Marcos Casagrande

Reputation: 40404

Just use JSON.parse

JSON.parse(xmlhttp.responseText);

Upvotes: 2

Related Questions