Javascript 读取一个简单的JSON数组
我正在尝试发送一个简单的数组,但它不起作用。我只想同时发送所有数组并读取containerName和containerStatus 我的第一个console.log输出这个 {“containerName”:“123”,“containerStatus”:“最多2小时”}{“containerName”:“ingesdev”,“containerStatus”:“最多2小时”} 爪哇 VM362:1未捕获的语法错误:JSON中位置处的意外标记{ 54 在JSON.parse()处 在Object.success(dashboard.js:10) at i(jquery.min.js:2) 在Object.fireWith[as resolveWith](jquery.min.js:2) 在A(jquery.min.js:4) 在XMLHttpRequest上。(jquery.min.js:4)Javascript 读取一个简单的JSON数组,javascript,Javascript,我正在尝试发送一个简单的数组,但它不起作用。我只想同时发送所有数组并读取containerName和containerStatus 我的第一个console.log输出这个 {“containerName”:“123”,“containerStatus”:“最多2小时”}{“containerName”:“ingesdev”,“containerStatus”:“最多2小时”} 爪哇 VM362:1未捕获的语法错误:JSON中位置处的意外标记{ 54 在JSON.parse()处 在Object
/Containers
或http://localhost:8080/containers
?我的意思是,数据的路径是什么containers[0]。fieldName
您没有将有效的JSON返回给客户端。顶层不能有多个连续对象。顶层应该有一个包含这些对象的数组 服务器端:
JSONArray jsonArray = new JSONAarray();
for (Container container:runningContainers) {
JSONObject obj = new JSONObject();
obj.put("containerName", container.getNames()[0].replace("/",""));
obj.put("containerStatus",container.getStatus());
jsonArray.put(obj);
}
response.getWriter().write(jsonArray.toString());
客户端:
$.ajax({
type: 'post',
url: 'Containers',
success: function (result) {
JSON.parse(result).forEach(function(container) {
console.log(container.containerName);
});
},
error: function() {
}
});
您没有向客户端返回有效的JSON。在顶层不能有多个连续的对象。在顶层应该有一个包含这些对象的数组。或者只返回一个对象。我想同时返回所有对象,但在使用时这些对象都过多了。请放置,以便我只能看到最后一个。正如我所说的,哟你必须创建一个对象数组。请检查我的编辑。
JSONArray jsonArray = new JSONAarray();
for (Container container:runningContainers) {
JSONObject obj = new JSONObject();
obj.put("containerName", container.getNames()[0].replace("/",""));
obj.put("containerStatus",container.getStatus());
jsonArray.put(obj);
}
response.getWriter().write(jsonArray.toString());
$.ajax({
type: 'post',
url: 'Containers',
success: function (result) {
JSON.parse(result).forEach(function(container) {
console.log(container.containerName);
});
},
error: function() {
}
});