繁体   English   中英

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

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

我正在尝试更深层次的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() {
    // ...
});

暂无
暂无

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

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