jquery代码:
1 $.ajax({ 2 url:url, 3 type:'post', 4 data:{"key1": "value1", "key2": "value2"}, 5 dataType:'json', 6 error:function(){}, 7 success:function(result){ 8 $("#id").html(result.key1); 9 } 10 });
java代码:
1 public String testAjax(){ 2 3 response.setContentType("application/x-json"); 4 response.setCharacterEncoding("UTF-8"); 5 6 String value1 = request.getParameter("key1"); 7 String value2 = request.getParameter("key2"); 8 String value3 = request.getParameter("key3"); 9 10 Map<String, Object> map = new HashMap<String, Object>(); 11 map.put("key1", value1); 12 map.put("key2", value2); 13 map.put("key3", value3); 14 15 PrintWriter out = null; 16 try{ 17 out.response.getWriter(); 18 //将map转换成json格式,具体用法及所需jar包可以参考官方文档 19 JSONObject result = JSONObject.fromObject(map); 20 out.print(result); 21 out.flush(); 22 }catch(IOException e){ 23 e.printStackTrace(); 24 }finally{ 25 if(out != null){ 26 out.close(); 27 } 28 } 29 return null; 30 }