Reputation: 33
I'm trying to send a simple array but it's not working. I just want to send all the array at the same time and read containerName and containerStatus.
My first console.log outputs this.
{"containerName":"123","containerStatus":"Up 2 hours"}{"containerName":"ingesdev","containerStatus":"Up 2 hours"}
Java
List<Container> runningContainers = dockerClient.listContainersCmd()
.exec();
JSONObject jsonContainer = new JSONObject();
for (Container container:runningContainers) {
jsonContainer.put("containerName", container.getNames()[0].replace("/",""));
jsonContainer.put("containerStatus",container.getStatus());
response.getWriter().write(jsonContainer.toString());
}
JavaScript
$.ajax({
type: 'post',
url: 'Containers',
success: function (result) {
console.log(result);
var container = container = JSON.parse(result);
console.log(container.containerName);
},
error: function() {
}
});
VM362:1 Uncaught SyntaxError: Unexpected token { in JSON at position 54 at JSON.parse () at Object.success (dashboard.js:10) at i (jquery.min.js:2) at Object.fireWith [as resolveWith] (jquery.min.js:2) at A (jquery.min.js:4) at XMLHttpRequest. (jquery.min.js:4)
Upvotes: 0
Views: 159
Reputation: 816404
You are not returning valid JSON to the client. You cannot have multiple consecutive objects at the top level. You should have an array at the top level that contains the objects.
Server side:
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());
Client side:
$.ajax({
type: 'post',
url: 'Containers',
success: function (result) {
JSON.parse(result).forEach(function(container) {
console.log(container.containerName);
});
},
error: function() {
}
});
Upvotes: 1
Reputation:
You should return once on your Java side the objects inside an JSONArray, after putting the objects inside the array with loop.
Is the URL correct? Maybe /Containers
or http://localhost:8080/containers
? so, I mean what is the path to data?
After parsing the data, you access your elements through index: containers[0].fieldName
Upvotes: 0