简体   繁体   English

Javascript Vanilla Ajax将响应转换为对象数组?

[英]Javascript vanilla ajax turn response into array of objects?

I am trying to experiment with javascript on a deeper level. 我正在尝试更深层次的javascript。 I am building my own $http object that has its own http methods. 我正在构建自己的具有自己的http方法的$http对象。

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. 在服务器上,我返回带有请求的JSON对象数组。

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}] . 在客户端上,我似乎收到了一个字符串[{"name":"Mike","points":33},{"name":"Shaq","points":16}]

How can I effectively convert the client side response to an array of JSON objects? 如何有效地将客户端响应转换为JSON对象数组?

只需使用JSON.parse

JSON.parse(xmlhttp.responseText);

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 . 您正在寻找JSON.parse Where you put it depends on if your $http object will only be getting JSON responses or not. 放置的位置取决于$http对象是否仅获取JSON响应。 If it does, then put your JSON.parse in what you send to success : 如果是这样,则将JSON.parse放入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. 但是,如果您还想接受其他类型的请求,则将JSON.parse放入成功的回调中。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM