JSP傳遞數據時不方便使用Java中的對象類型,一般使用JSON來傳遞對象。
在使用JSON時,前端js如下,注意指定dataType:
var htmlobj= $.ajax({ url:"chat.do",type:"POST", data:{sayingContent:$("#textarea").val()}, dataType:"json", success: function(data){$("#said").append(data.content);} });
后台要引入如下jar包。

然后使用如下方式保存JSON:
Map map = new HashMap(); map.put("content", request.getParameter("sayingContent")); JSONObject json = JSONObject.fromObject(map);
后台訪問時,代碼如下:
json.getString("content")
返回數據時,要注意設置數據格式,以保證JSON的數據不會成為亂碼:
response.setContentType("text/html; charset=utf-8");
response.getWriter().print(json);
最后,區分一下response.getWriter()的write()和print()方法的區別:
(1 )write():僅支持輸出字符類型數據,字符、字符數組、字符串等;
(2) print():可以將各種類型(包括Object)的數據通過默認編碼轉換成bytes字節形式,這些字節都通過write(int c)方法被輸出。
一個完整樣例如下:
protected void doPost(HttpServletRequest request,HttpServletResponse response){ Map map = new HashMap(); map.put("content", request.getParameter("sayingContent")); JSONObject json = JSONObject.fromObject(map); try { response.setContentType("text/html; charset=utf-8"); response.getWriter().print(json); } catch (IOException e) { e.printStackTrace(); } }
后台JSON的擴展閱讀:
JSON存取:http://www.cnblogs.com/lanxuezaipiao/archive/2013/05/23/3096001.html
JSON亂碼:http://www.iteye.com/problems/87358
