Jquery + Ajax + Json binding

Source: Internet
Author: User

The entire process is extremely simple for skilled people. You can use a simple ajax request to obtain the json string returned by the general processing page, parse the returned json string on the page, and bind it to the corresponding list.
Page code:
[Html]
<% @ Page Title = "" Language = "C #" MasterPageFile = "~ /Site. Master "AutoEventWireup =" true "CodeBehind =" Default. aspx. cs "Inherits =" MyTestWebApp. JsonData. Default "%>
<Asp: Content ID = "Content1" ContentPlaceHolderID = "HeadContent" runat = "server">
<Script src = "../Scripts/jquery-1.4.1.min.js" type = "text/javascript"> </script>
<Script type = "text/javascript">
<Pre name = "code" class = "javascript"> $ (document). ready (function (){
$. Ajax ({
Type: "get ",
DataType: "Json ",
Url: "JsonHandler. ashx ",
Start: function () {alert ("getting data started ")},
Complete: function () {alert ("obtained ")},
Success: function (data ){
Var t = eval (data); // forcibly convert the json string to generate a json object
$. Each (t, function (I, n ){
Var row = $ ("# template"). clone (); // clone template to create a new data row
For (attribute in n ){
Row. find ("#" + attribute).html (n [attribute]); // loop the attributes of the json object and assign values to the corresponding columns in the Data row, the column id is the corresponding attribute name.
}
Row. appendTo ($ ("# testTable "));
});
}
});
});

</Script> </asp: Content> <asp: content ID = "Content2" ContentPlaceHolderID = "MainContent" runat = "server"> <table id = "testTable"> <th> NO. </th> <th> title </th> <th> content </th> <! -- Data Template --> <! -- The id of each column is the name of the column in the corresponding record --> <tr id = "template"> <td id = "Id"> </td> <td id = "title "> </td> <td id =" content "> </td> </tr> <! -- Data Template --> </table> </asp: Content>


General Page code:
[Csharp]
Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Web;
Using MyTestWebApp. Code;
Using System. Data;
 
Namespace MyTestWebApp. JsonData
{
/// <Summary>
/// Summary of JsonHandler
/// </Summary>
Public class JsonHandler: IHttpHandler
{
 
Public void ProcessRequest (HttpContext context)
{
Context. Response. ContentType = "text/javascript ";
DataTable table = SqlHelper. ExecuteDataset (SqlHelper. connectionString, CommandType. Text, "select Id, title, content from Accordion"). Tables [0];
Context. Response. Write (JSONHelper. DataTableToJSON (table ));
}
 
Public bool IsReusable
{
Get
{
Return false;
}
}
}
}

JSONHelper. cs (I am looking for someone else to write JSONHelper. cs)
[Csharp]
Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Web;
Using System. Web. Script. Serialization;
Using System. Data;
 
Namespace MyTestWebApp. Code
{
/// <Summary>
/// JSON help class
/// </Summary>
Public class JSONHelper
{
/// <Summary>
/// Convert the object to JSON
/// </Summary>
/// <Param name = "obj"> Object </param>
/// <Returns> JSON string </returns>
Public static string ObjectToJSON (object obj)
{
JavaScriptSerializer jss = new JavaScriptSerializer ();
Try
{
Return jss. Serialize (obj );
}
Catch (Exception ex)
{

Throw new Exception ("JSONHelper. ObjectToJSON ():" + ex. Message );
}
}
 
/// <Summary>
/// Data table key-value pair set www.2cto.com
/// Convert the DataTable into a List set and store each row
/// The set contains the key-Value Pair dictionary, storing each column
/// </Summary>
/// <Param name = "dt"> data table </param>
/// <Returns> hash table array </returns>
Public static List <Dictionary <string, object> DataTableToList (DataTable dt)
{
List <Dictionary <string, object> list
= New List <Dictionary <string, object> ();
 
Foreach (DataRow dr in dt. Rows)
{
Dictionary <string, object> dic = new Dictionary <string, object> ();
Foreach (DataColumn dc in dt. Columns)
{
Dic. Add (dc. ColumnName, dr [dc. ColumnName]);
}
List. Add (dic );
}
Return list;
}
 
/// <Summary>
/// Array dictionary
/// </Summary>
/// <Param name = "dataSet"> dataSet </param>
/// <Returns> key-Value Pair array dictionary </returns>
Public static Dictionary <string, List <Dictionary <string, object> DataSetToDic (DataSet ds)
{
Dictionary <string, List <Dictionary <string, object >>> result = new Dictionary <string, List <Dictionary <string, object >>> ();
 
Foreach (DataTable dt in ds. Tables)
Result. Add (dt. TableName, ableabletolist (dt ));
 
Return result;
}
 
/// <Summary>
/// Convert the data table to JSON
/// </Summary>
/// <Param name = "dataTable"> data table </param>
/// <Returns> JSON string </returns>
Public static string DataTableToJSON (DataTable dt)
{
Return ObjectToJSON (DataTableToList (dt ));
}
 
/// <Summary>
/// Convert JSON text to object, generic Method
/// </Summary>
/// <Typeparam name = "T"> type </typeparam>
/// <Param name = "jsonText"> JSON text </param>
/// <Returns> specified object type </returns>
Public static T JSONToObject <T> (string jsonText)
{
JavaScriptSerializer jss = new JavaScriptSerializer ();
Try
{
Return jss. Deserialize <T> (jsonText );
}
Catch (Exception ex)
{
Throw new Exception ("JSONHelper. JSONToObject ():" + ex. Message );
}
}
 
/// <Summary>
/// Convert the JSON text to the data table
/// </Summary>
/// <Param name = "jsonText"> JSON text </param>
/// <Returns> data table dictionary </returns>
Public static Dictionary <string, List <Dictionary <string, object> TablesDataFromJSON (string jsonText)
{
Return JSONToObject <Dictionary <string, List <Dictionary <string, object >>> (jsonText );
}
 
/// <Summary>
/// Convert JSON text into data rows
/// </Summary>
/// <Param name = "jsonText"> JSON text </param>
/// <Returns> data row dictionary </returns>
Public static Dictionary <string, object> DataRowFromJSON (string jsonText)
{
Return JSONToObject <Dictionary <string, object> (jsonText );
}
}
}


From the column of QQlvbo

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.