Jquery parses json data in detail

  • 2020-03-30 01:03:46
  • OfStack

Recently, I was tortured by jquery for a while, so I made a demo of jquery parsing json. This demo wants to realize instantiating dataSet or dataTable dataSet from the asp.net background, convert dataSet into json and return it to the client.

Start with a brief introduction to the getJson method

Jquery getJson (url, [data], [callback])

Url: send the request address.
Data: to send Key/value parameter.
Callback: a callback function that successfully loads.

The following is the actual getJson method

First, create a helper class to convert the dataset into a json string


 public static string DataTableToJson(string jsonName, DataTable dt)
        {
            StringBuilder Json = new StringBuilder();
            Json.Append("{"" + jsonName + "":[");
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    Json.Append("{");
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        Json.Append(""" + dt.Columns[j].ColumnName.ToString() + "":"" + dt.Rows[i][j].ToString() + """);
                        if (j < dt.Columns.Count - 1)
                        {
                            Json.Append(",");
                        }
                    }
                    Json.Append("}");
                    if (i < dt.Rows.Count - 1)
                    {
                        Json.Append(",");
                    }
                }
            }
            Json.Append("]}");
            return Json.ToString();
        }

This method is a helper class method on MSDN.

The second step is to manually configure and create a demo Dataset, but in a project you typically get the data from a database or from a service


 public static DataSet BindData()
        {
            DataTable dtData = new DataTable();
            dtData.Columns.Add("id");
            dtData.Columns.Add("name");
            dtData.Columns.Add("sex");
            DataRow drData;
            drData = dtData.NewRow();
            drData[0] = 16;
            drData[1] = "zhaoliu";
            drData[2] = "man";
            dtData.Rows.Add(drData);
            drData = dtData.NewRow();
            drData[0] = 19;
            drData[1] = "zhangsan";
            drData[2] = "women";
            dtData.Rows.Add(drData);
            DataSet ds = new DataSet();
            ds.Tables.Add(dtData);
            return ds;
        }

Step 3: create the aspx page

Foreground page: two buttons, one to click to begin parsing json data and one to view the json string


<head runat="server">
    <title></title>
    <script language="javascript" type="text/javascript" src="Scripts/jquery-1.4.1.min.js"></script>
    <script language="javascript" type="text/javascript">
        $(function () {
            $("#btn").click(function () {
                $.getJSON("GetJsonDemo.aspx", { Action: "action" },
                 function (data) {
                     var txt = "";
                     $.each(data, function (k, v) { $.each(v, function (m, n) { txt += "id :"+n.id + ";name :" + n.name + ";sex :"+n.sex+"<br/>" }); });
                     $("#txt").html(txt);
                 });
            });
         });
         $(function () {
             $("#btn2").click(function () {
                 $.get("GetJsonDemo.aspx", { Action: "action" },
                 function (data) { $("#txt2").text(data); });
             });
         });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <input id="btn" type="button" value="paser json" /><br />
        <input id="btn2" type="button" value="watch json string" /><br />
        <label id="txt"></label><br />
         <label id="txt2"></label>
    </div>
    </form>
</body>

Background page:

 protected void Page_Load(object sender, EventArgs e)
        {
            JsonAjax();
        }
        private void JsonAjax() {
            string action = Request["Action"];
            if (!string.IsNullOrEmpty(action) && action == "action")  //To determine whether it came in through the foreground click event
            {
                string str = DataTableConvertJson.DataTableToJson("json", Data.BindData().Tables[0]);
                Response.Write(str);
                Response.End();
            }
        }

Finally, I'll show you the generated json format:

The Top of the Form

{" json ": [{" id" : "16", "name" : "zhaoliu", "sex" : "man"}, {" id ":" 19 ", "name" : "zhangsan", "sex", "" women"}]}

Bottomof the Form


Related articles: