歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux編程 >> Linux編程

jQuery解析JSON數據

JSON (JavaScript Object Notation) 是一種輕量級的數據交換格式,易於人閱讀和編寫,同時也易於機器解析和生成,而且它是基於JavaScript 的。 JSON采用完全獨立於語言的文本格式,但是也使用了類似於C語言家族的習慣(包括C, C++, C#, Java, JavaScript 等)。這些特性使JSON成為理想的數據交換語言
  JSON有兩種結構:
①“名/值”對的集合(A collection of name/value pairs)。在不同的語言中,它被理解為對象,結構,關聯數組等
②值的有序列表(An ordered list of values)。在大部分語言中,它被理解為數組。   JSON數據有嚴格的格式,只有按照這個格式,才可以進行有效的解析   JSON表示名稱/值對:
{ "firstName": "Brett" }
  多個名稱/值對串在一起:
{ "firstName": "Brett", "lastName":"McLaughlin", "email": "[email protected]" }
從語法方面來看,這與名稱/值對相比並沒有很大的優勢,www.linuxidc.com但是在這種情況下 JSON
更容易使用,而且可讀性更好
當需要表示一組值時,JSON 不但能夠提高可讀性,而且可以減少復雜性:
{ “employees": [
  { "firstName": "Brett", "lastName":"McLaughlin", "email": "[email protected]" },
  { "firstName": "Jason", "lastName":"Hunter", "email": "[email protected]" },
  { "firstName": "Elliotte", "lastName":"Harold", "email": "[email protected]" }
] }     Juqery解析JSON數據   例子一:   ①建立.ashx文件。 /// <summary>
    /// $codebehindclassname$ 的摘要說明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class JsonHandler : IHttpHandler
    {         public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string data = "[{name:\"Tom\",age:\"26\"},{name:\"Jim\",age:\"27\"}]";
            context.Response.Write(data);
        }         public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }   ②前台解析JSON數據 <head runat="server">
    <title></title>     <script src="js/jquery-1.3.2.js" type="text/javascript"></script>     <script type="text/javascript">
        $(function() {
            $.getJSON(
        "JsonHandler.ashx",
         function(data) {
             $.each(data, function(i) {
                 $("#cat-list").append("<li>name:" + data[i].name + "&nbsp; Age:" + data                  [i].age+ "</li>")
             });
         });
        });  
    </script> </head>
<body>
    <form id="form1" runat="server">
    <div>
    <ul id="cat-list"></ul>
    </div>
    </form>
</body>     例子二:   ①建立頁面處理後台,.aspx public partial class AutoDB2 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            StringBuilder str = new StringBuilder();
            string strCon = @"Data Source=.\SQLEXPRESS;Initial                                   Catalog=TeacherFiles;User ID=sa;pwd=as";
            SqlConnection con = new SqlConnection(strCon);
            string sql = string.Format("select TeacherNum,TeacherName from                                TeacherBasicInformation");
            SqlDataAdapter sda = new SqlDataAdapter(sql, con);
            DataTable dt = new DataTable();
            sda.Fill(dt);             foreach (DataRow dr in dt.Rows)
            {
                str.AppendFormat                ("{{name:\"{0}\",value:\"{1}\"}},", dr["TeacherName"], dr["TeacherNum"]);
            }             Response.Write("[" + str.ToString().TrimEnd(',') + "]");
            Response.End();
        }
    }   ②前台解析JSON數據 <head runat="server">
    <title></title>     <script type="text/javascript" src="js/jquery-1.3.2.js"></script>     <script type="text/javascript" src="js/jquery.autocomplete.js"></script>     <link rel="Stylesheet" href="css/jquery.autocomplete.css" type="text/css" />     <script type="text/javascript">
        $(function() {
            $.getJSON(
            "AutoDB2.aspx", function(data) {
            $("#txt").autocomplete(data, {
                 minChars: 0,                            //cacheLength: 1,                      //multiple: true,                     matchContains: true,                     autoFill: false,                       mustMatch: true,                        //delay: 100,                            formatItem: function(row, i, max) {
                    return i + "/" + max + ": \"" + row.name + "\" [" + row.value + "]";
                }
                ,
                formatMatch: function(row, i, max) {
                  return row.name+" "+row.value;
                }
                ,
                formatResult: function(row) {
                  return row.name;
                }
                });
            });
        });         $(function() {
        function findValueCallback(event, data, formatted) {
            $("#content").html("<strong>" + (!data ? "無匹配項!" : "Selected: " + formatted)               + "</strong>");
        }         $("#txt").result(findValueCallback);
        $("#btngetvalue").click(function() { $("#txt").search(); });
        });
    </script> </head>
<body>
    <form id="form1" runat="server">
    <div>
        示例:<input id="txt" runat="server" type="text" />
        <input id="btngetvalue" type="button" value="Get Value" /><br /><span id="content"></span>
    </div>
    </form>
</body>
Copyright © Linux教程網 All Rights Reserved