在JSP中使用JsonArray的Ajax jquery
我正在使用JSon-RPC库 。
Servlet的:
我想将List
放入JSonArray
,与{["name":"AAA","age":"24"]["name":"BBB","age":"12"]}
。 JsonArray
有一个构造JsonArray
,它接受一个与参数相同的Collection
。 如果result是一个JsonObject
那么我将使用方法out.print(instanceJsonObject.toString())
响应客户端。 现在我不知道如何从服务器到客户端响应JsonArray
。
ArrayList list = new ArrayList(); list.add(new Student("Vu Duc Hoan", "C1010G", "24")); list.add(new Student("Vu Duc Hoan2", "C1010G2", "242")); JSONObject js = new JSONObject(); org.json.JSONArray array = new JSONArray(list);
客户:
你能告诉我如何在JsonArray中获取数据吗? 我正在使用$.getJson
btnJson.click(function(){ $.getJSON("../DemoAjax/Controller?action=getJson",function(data){ });
我认为这是您正在寻找的servlet代码,但我认为您需要首先将Student
对象转换为JSONObject
,然后将JSONObject
放在JSONArray
,本教程可能会帮助您:
JSONObject js = new JSONObject(); org.json.JSONArray jsonArray = new JSONArray(list); // set the response content-type response.setContentType("application/json"); PrintWriter out = response.getwriter(); // writing the json-array to the output stream out.print(jsonArray); out.flush();
在javascript方法中, function(data)
将包含此json数组,您可以使用此答案来获取html页面中的数据。