日期:2014-05-16 浏览次数:20757 次
<script type="text/javascript"> $(document).ready(function(){ $("#btncheck").click(function(){ var userdata= { "users": [ {"name":"user1", "sex":"m", "age":"20"}, {"name":"user2", "sex":"f", "age":"21"} ] }; var user = JSON.stringify(userdata); $.ajax({ url: '/webtemplate/site.ajax.json.do?method=validate', type: 'post', data: 'user=' + user, dataType: 'json', timeout: 1000, error: function() { alert('Error!'); }, success: function(result) { alert(result); } }); }); }); </script> </head> <body> <form action="#" method="post"> <input type="button" id="btncheck">JQueryJson测试</input> </form> </body> </html>
public ActionForward validate(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws Exception { String myJson = request.getParameter("user"); // 转化为JSON对象 JSONObject json = new JSONObject(myJson); // 获取对应的数组 JSONArray array = json.getJSONArray("users"); for (int i = 0; i < array.length(); i++) { // 获取对应数组的每一个对象 JSONObject thisJson = (JSONObject) array.get(i); log.info(thisJson.get("name") + " - " + thisJson.get("sex") + " - " + thisJson.get("age")); } String book = "{'name':'chinese','publish':'china','price':30}"; JSONObject.fromObject(book); response.setContentType("application/x-json"); PrintWriter out = response.getWriter(); out.println(book.toString()); out.flush(); out.close(); return null; }