This article mainly introduces Jquery's parsing of json data in detail. If you need it, you can refer to it. I hope it will be helpful to anyone who has been tortured by jquery recently, A jquery json parsing demo is provided. This demo is used to instantiate a dataSet or able dataSet from the asp.net background, convert the dataSet to json, and return it to the client, the client parses the code using jquery getJson and displays it on the page.
First, let's briefly introduce the getJson method.
Jquery. getJson (url, [data], [callback])
Url: The sending request address.
Data: Key/value parameter to be sent.
Callback: callback function when the load is successful.
The following is the getJson method.
Create a helper class to convert a dataset to a json string.
The Code is as follows:
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 an auxiliary class method on msdn.
Step 2: manually create a demo Dataset, but in the project, data is generally obtained from the database or service.
The Code is as follows:
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 An aspx page
Front-end page: two buttons, one clicking to start parsing json data, and the other viewing json strings
The Code is as follows: