时间:2021-07-01 10:21:17 帮助过:73人阅读
先来看看我们的Json数据格式:
为了消除乱码问题,我们设置一个过滤器(代码片段)
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
resp.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=UTF-8");
chain.doFilter(req, resp);
}
服务端我用Servlet生成json数据(代码片段)。
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter(); //过滤器已经做过编码转化了。 resp.setContentType("text/html;charset=UTF-8");
StringBuffer sb = new StringBuffer();
sb.append("[{id:01,name:\"小白\",old:29,sex:\"男\"},");
sb.append("{id:02,name:\"小蓝\",old:29,sex:\"男\"},");
sb.append("{id:03,name:\"小雅\",old:29,sex:\"男\"}]");
out.print(sb);
}
页面端JQuery代码:
之前为了省事,我层把json数据写到json.txt,json.jsp中,不用Servlet封装,可是后来我用Firebug调试了一下

写到.jsp、.txt文件中的json数据,没有被解析出来,Firebug中调试了一下,10行断点下一步直接结束,
就没有遍历对象数组。于是分别测试了一下
文本文件 json.txt
jsp文件 json.jsp
Servlet json.do
返回的数据,浏览器只有解析出Servlet的返回的数据是json数据

希望本文所述对大家jQuery程序设计有所帮助。