I am trying multiple values to return from my server to AJAX in Java. For now, I use this approach, but it's not a good solution:
Javascript:
success: function(list) {
var firstValue = list[0];
var secondValue = list[1];
var thirdValue = list[2];
}
Java:
ArrayList<ArrayList<String>> list = new ArrayList<ArrayList<String>>();
list.add(infoFirstValue());
list.add(infoThirdValue());
list.add(infoThirdValue());
String glist = gson.toJson(list);
response.getWriter().write(glist);
Is it possible to return several values or an object or an other solution?
If it helps, here's some code snippets based on yours above, showing how to switch to an object-style response instead of an array. Gson includes the class JsonObject
which might be the simplest thing for you to use: http://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/JsonObject.html
However, Gson's way more powerful than that -- you can actually just serialize a plain old Java object directly, which is probably more elegant than the intermediate step of converting existing data to a JsonObject
(see this existing answer: https://stackoverflow.com/questions/1668862/good-json-java-library/1668951#1668951). At the very least, the info*Value()
methods would probably be better served as methods of an object you were serializing. And instead of storing the returned object properties as functionally-scoped variables in JavaScript, I presume you could just pass the object around and access its properties.
JAVA
JSONObject rv = new JSONObject();
rv.add("firstValue", infoFirstValue());
rv.add("secondValue", infoSecondValue());
rv.add("thirdValue", infoThirdValue());
String gobject = gson.toJson(rv);
response.getWriter().write(gobject);
JAVASCRIPT
success: function(obj){
var firstValue = obj.firstValue;
var secondValue = obj.secondValue;
var thirdValue = obj.thirdValue;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With