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() {
// ...
});
相关文章:
- Javascript(Angular)从一个对象数组到第二个数组查找值
- 在Javascript中转换对象数组
- 在JavaScript中通过索引从对象数组中获取值
- Backbone虹吸以获取对象数组
- 如何在DataTables 2.1中迭代对象数组
- Javascript-根据赋值顺序,按键合并对象数组
- 将事件附加到对象/数组
- jQuery$.inArray()总是返回-1和一个对象数组
- javascript处理一个对象数组以获得一个新的对象数组
- javascript在数组中获取对象数组中键的所有不同值
- 在对象数组中查找多个值的d3范围
- Undercore.js获取对象数组中键对象的值
- 在mongoose中使用正则表达式在对象数组中进行查询搜索
- 如何通过json对象数组为嵌套对象赋值
- 如何循环通过2个对象数组并通过匹配id进行合并
- 为对象数组创建列表项
- 如何使用javascript合并两个对象数组
- JSON到对象数组,并向每个对象添加项
- JavaScript:从对象数组中获取唯一值及其计数
- 按不同项目对对象数组进行排序