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

Javascript vanilla ajax turn response into array of objects?

本文关键字:对象 数组 转换 响应 vanilla ajax Javascript      更新时间:2023-09-26

我正在尝试更深层次的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 对象数组?

只需使用JSON.parse

JSON.parse(xmlhttp.responseText);

即使评论已经回答了这个问题,我觉得我也可以抛出一个实际的答案(加上澄清把它放在哪里!

你正在寻找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() {
    // ...
});