Home >Web Front-end >JS Tutorial >jQuery parsing json data example analysis_jquery
This article analyzes the method of jQuery parsing json data through examples. Share it with everyone for your reference, the details are as follows:
Let’s take a look at our Json data format first:
[ {id:01,name:"小白",old:29,sex:"男"}, {id:02,name:"小蓝",old:29,sex:"男"}, {id:03,name:"小雅",old:29,sex:"男"} ]
In order to eliminate the problem of garbled characters, we set up a filter (code snippet)
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); }
On the server side, I use Servlet to generate json data (code snippet).
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 code on the page:
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head><title>json学习</title> <meta content="text/html; charset=UTF-8" http-equiv="Content-Type"> <script type="text/javascript" src="jslib/jquery.js" charset="UTF-8"></script> <script type="text/javascript" charset="UTF-8"> $(document).ready(function() { var select = $("#select"); $.get("json.do", null, function(data) { var jsonData = eval(data);//接收到的数据转化为JQuery对象,由JQuery为我们处理 $.each(jsonData, function(index, objVal) { //遍历对象数组,index是数组的索引号,objVal是遍历的一个对象。 //val["属性"]可取到对应的属性值。 $("<option>").attr("value", objVal["id"]).html(objVal["name"]).appendTo(select); }); }); }); </script> </head> <body> <select id="select"></select> </body> </html>
In order to save trouble before, I wrote the json data into json.txt and json.jsp without using Servlet encapsulation, but then I used Firebug to debug it
The json data written to .jsp and .txt files was not parsed. I debugged it in Firebug and found that the breakpoint at line 10 ended directly in the next step.
There is no traversing the object array. So I tested them separately
Text file json.txt
jsp file json.jsp
Servlet json.do
For the returned data, the browser can only parse the data returned by the Servlet as json data
I hope this article will be helpful to everyone in jQuery programming.