Javascript vanilla ajax将响应转换为对象数组?

时间:2016-01-25 01:56:24

标签: javascript arrays json ajax

我正试图在更深层次上尝试使用javascript。我正在构建自己的$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();
};

在服务器上,我返回了一个带有请求的JSON对象数组。

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

在客户端上,我似乎得到一个字符串[{"name":"Mike","points":33},{"name":"Shaq","points":16}]

如何有效地将客户端响应转换为JSON对象数组?

2 个答案:

答案 0 :(得分:2)

只需使用JSON.parse

即可
JSON.parse(xmlhttp.responseText);

答案 1 :(得分:2)

尽管评论已经回答了这个问题,但我觉得我可能会抛出一个实际的答案(另外还要说明放在哪里!)

您正在寻找JSON.parse。你把它放在哪里取决于你的$http对象是否只会获得JSON响应。如果是,请将您的JSON.parse放入发送到success的内容:

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

但是,如果您还想接受其他类型的请求,请将您的JSON.parse放入成功的回调中。

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