欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

jQuery解析json數(shù)據(jù)實(shí)例分析

 更新時(shí)間:2015年11月24日 10:09:56   作者:xiaofancn  
這篇文章主要介紹了jQuery解析json數(shù)據(jù)的具體實(shí)現(xiàn)方法,結(jié)合實(shí)例形式較為詳細(xì)的分析了jQuery解析json格式數(shù)據(jù)的相關(guān)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下

本文實(shí)例分析了jQuery解析json數(shù)據(jù)的方法。分享給大家供大家參考,具體如下:

先來(lái)看看我們的Json數(shù)據(jù)格式:

[
{id:01,name:"小白",old:29,sex:"男"},
{id:02,name:"小藍(lán)",old:29,sex:"男"},
{id:03,name:"小雅",old:29,sex:"男"}
]

為了消除亂碼問(wèn)題,我們?cè)O(shè)置一個(gè)過(guò)濾器(代碼片段)

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);
}

服務(wù)端我用Servlet生成json數(shù)據(jù)(代碼片段)。

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    PrintWriter out = response.getWriter(); //過(guò)濾器已經(jīng)做過(guò)編碼轉(zhuǎn)化了。 resp.setContentType("text/html;charset=UTF-8");
    StringBuffer sb = new StringBuffer();
    sb.append("[{id:01,name:\"小白\",old:29,sex:\"男\(zhòng)"},");
    sb.append("{id:02,name:\"小藍(lán)\",old:29,sex:\"男\(zhòng)"},");
    sb.append("{id:03,name:\"小雅\",old:29,sex:\"男\(zhòng)"}]");
    out.print(sb);
}

頁(yè)面端JQuery代碼:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>json學(xué)習(xí)</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);//接收到的數(shù)據(jù)轉(zhuǎn)化為JQuery對(duì)象,由JQuery為我們處理
        $.each(jsonData, function(index, objVal) { //遍歷對(duì)象數(shù)組,index是數(shù)組的索引號(hào),objVal是遍歷的一個(gè)對(duì)象。
          //val["屬性"]可取到對(duì)應(yīng)的屬性值。
          $("<option>").attr("value", objVal["id"]).html(objVal["name"]).appendTo(select);
        });
      });
    });
  </script>
</head>
<body>
<select id="select"></select>
</body>
</html>

之前為了省事,我層把json數(shù)據(jù)寫(xiě)到j(luò)son.txt,json.jsp中,不用Servlet封裝,可是后來(lái)我用Firebug調(diào)試了一下

寫(xiě)到.jsp、.txt文件中的json數(shù)據(jù),沒(méi)有被解析出來(lái),F(xiàn)irebug中調(diào)試了一下,10行斷點(diǎn)下一步直接結(jié)束,

就沒(méi)有遍歷對(duì)象數(shù)組。于是分別測(cè)試了一下

 文本文件  json.txt
 jsp文件   json.jsp
 Servlet   json.do

返回的數(shù)據(jù),瀏覽器只有解析出Servlet的返回的數(shù)據(jù)是json數(shù)據(jù)

希望本文所述對(duì)大家jQuery程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評(píng)論