jQuery+Ajax +Json绑定


整个过程对于熟练的人来说简单无比,通过简单的ajax请求获取一般处理页面返回的json字符串,在页面对返回的json字符串进行解析,并绑定到对应的列表。

页面代码:

  1. <%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="MyTestWebApp.JsonData.Default" %>  
  2. <asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">  
  3.     <script src="../Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>  
  4.     <script type="text/javascript">  
  5.         <pre name="code" class="javascript">$(document).ready(function () {  
  6.             $.ajax({  
  7.                 type: "get",  
  8.                 dataType: "Json",  
  9.                 url: "JsonHandler.ashx",  
  10.                 start: function () { alert("开始获取数据了") },  
  11.                 complete: function () { alert("获取完了") },  
  12.                 success: function (data) {  
  13.                     var t = eval(data); //强制转换一下json字符串,生成json对象  
  14.                     $.each(t, function (i, n) {  
  15.                         var row = $("#template").clone(); //克隆模板,创建一个新数据行  
  16.                         for (attribute in n) {  
  17.                             row.find("#" + attribute).html(n[attribute]); //循环json对象的属性,并赋值到数据行中对应的列,此处列的id就是相应的属性名称  
  18.                         }  
  19.                         row.appendTo($("#testTable"));  
  20.                     });  
  21.                 }  
  22.             });  
  23.         });  
</script></asp:Content><asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"><table id="testTable"> <th>编号</th><th>标题</th><th>内容</th> <!--数据模板--> <!--其中每一列的id就是对应记录中的列名--> <tr id="template"><td id="Id"></td><td id="title"></td><td id="content"></td></tr> <!--数据模板--></table></asp:Content>

一般处理页面代码:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using MyTestWebApp.Code;  
  6. using System.Data;  
  7.   
  8. namespace MyTestWebApp.JsonData  
  9. {  
  10.     /// <summary>   
  11.     /// JsonHandler 的摘要说明   
  12.     /// </summary>   
  13.     public class JsonHandler : IHttpHandler  
  14.     {  
  15.   
  16.         public void ProcessRequest(HttpContext context)  
  17.         {  
  18.             context.Response.ContentType = "text/javascript";  
  19.             DataTable table = SqlHelper.ExecuteDataset(SqlHelper.connectionString, CommandType.Text, "select Id, title, content from Accordion").Tables[0];  
  20.             context.Response.Write(JSONHelper.DataTableToJSON(table));  
  21.         }  
  22.   
  23.         public bool IsReusable  
  24.         {  
  25.             get  
  26.             {  
  27.                 return false;  
  28.             }  
  29.         }  
  30.     }  
  31. }  
  • 1
  • 2
  • 下一页

相关内容