0

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?

3
  • 3
    the response you're getting is JSON - you need to convert it to a javascript object using JSON.parse Commented Jan 25, 2016 at 1:58
  • Ok duh, everything else checks out? Commented Jan 25, 2016 at 1:59
  • Sorry, I didn't check the validity of the xmlhttprequest stuff Commented Jan 25, 2016 at 1:59

2 Answers 2

2

Just use JSON.parse

JSON.parse(xmlhttp.responseText);
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.