Obtain the dataset code from the background using jquery and json.

Source: Internet
Author: User

In fact, Json is a data format. Data is converted into a format in the background, and then parsed in the foreground using the same method, similar to serialization. Json format is mainly composed of key-value pairs, which can represent multiple data. For example

{Name: zhangsan, age: 12, class: 1}

Json can also represent a dataset consisting of {} And. For example, we need to query a table from the database and transmit the table to the foreground. However, dataset cannot be directly transmitted. We need to convert dataset data to json data, this allows the front-end js to parse data. Next I will write the conversion format.

{Name: Table Name, Rows: [{SName: Name, SAge: Age} {...}]} This is the data format of a table,

{Tables: [{Name: Table 1 Name, Rows: [{SName: Name, SAge: Age }{...} {...}]} {Name: Table 2 Name, Rows: [{SName: Name, SAge: Age }{...} {...}]} this is the data format of multiple tables.

The following example shows how to transmit a dataset.

First, we need a front-end page to obtain the data studentinfo.html. on this page, we have a function to obtain the data in Json format. jquery encapsulates such a function, JSON. parse ();

Copy codeThe Code is as follows:
<Script type = "text/javascript">
Function getData (){
$ ("# Data"). val ("");
JQuery. post ('../ashx_for_request/getdataset. ashx', {}, function (data) {// data is the data transmitted from the background
Var obj = JSON. parse (data); // convert the data transmitted the day after tomorrow to the Json format
$ ("# Data" pai.html ("");
$. Each (obj. Tables, function (index, table) {// traverse the dataset table and output the dataset content
// Display different fields based on different table names. Get a specific table, table = obj. Tables [0]
Var tableName = table. Name;
$. Each (table. Rows, function (index, row) {// traverse Rows in the dataset table
$ ("# Data" ).html ($ ("# data" ).html () + row. SID + row. SName + row. SAge + row. SClass + row. SSex + row. SGrade + "</br>"); // here we use row. colname to get the content of each column in each row
});
});
})
}
</Script>

We use the jquery post function to obtain data from the background and parse the data. Now I will demonstrate the background data format.
Copy codeThe Code is as follows:
Private String GetDataSet ()
{
System. Data. DataSet ds = new System. Data. DataSet ();
// Test Data
Using (System. Data. SqlClient. SqlConnection conn = new System. Data. SqlClient. SqlConnection ("server =.; database = Student; uid = sa; pwd = 123456 "))
{
Using (System. Data. SqlClient. SqlCommand com = conn. CreateCommand ())
{
Com. CommandText = "select * from BaseNews ";
System. Data. SqlClient. SqlDataAdapter da = new System. Data. SqlClient. SqlDataAdapter (com );
Da. Fill (ds );
}
}
Return Dataset2Json (ds );

}

/// <Summary>
/// DataTable converted to Json format
/// </Summary>
/// <Param name = "dt"> </param>
/// <Returns> </returns>
Public static string DataTable2Json (System. Data. DataTable dt)
{
StringBuilder jsonBuilder = new StringBuilder ();
JsonBuilder. Append ("{\" Name \ ": \" "+ dt. TableName +" \ ", \" Rows ");
JsonBuilder. Append ("\":[");
For (int I = 0; I <dt. Rows. Count; I ++)
{
JsonBuilder. Append ("{");
For (int j = 0; j <dt. Columns. Count; j ++)
{
JsonBuilder. Append ("\"");
JsonBuilder. Append (dt. Columns [j]. ColumnName );
JsonBuilder. Append ("\":\"");
JsonBuilder. append (dt. rows [I] [j]. toString (). replace ("\" "," \ ""); // special handling should also be performed for special characters.
JsonBuilder. Append ("\",");
}
JsonBuilder. Remove (jsonBuilder. Length-1, 1 );
JsonBuilder. Append ("},");
}
JsonBuilder. Remove (jsonBuilder. Length-1, 1 );
JsonBuilder. Append ("]");
JsonBuilder. Append ("}");
Return jsonBuilder. ToString ();
}

/// <Summary>
/// Convert DataSet to Json format
/// </Summary>
/// <Param name = "ds"> DataSet </param>
/// <Returns> </returns>
Public static string Dataset2Json (System. Data. DataSet ds)
{
StringBuilder json = new StringBuilder ();
Json. Append ("{\" Tables \":");
Json. Append ("[");
Foreach (System. Data. DataTable dt in ds. Tables)
{
Json. Append (DataTable2Json (dt ));
Json. Append (",");
}
Json. Remove (json. Length-1, 1 );
Json. Append ("]");
Json. Append ("}");
Return json. ToString ();
}

Let's take a look at the results.

You can give the corresponding format based on the obtained data.

Don't think it's done here. The Json format has compatibility issues in different browsers. In this case, you only need to download a json2 js file.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.