歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> jQuery+Ajax +Json綁定

jQuery+Ajax +Json綁定

日期:2017/3/1 10:28:03   编辑:Linux編程

整個過程對於熟練的人來說簡單無比,通過簡單的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. namespace MyTestWebApp.JsonData
  8. {
  9. /// <summary>
  10. /// JsonHandler 的摘要說明
  11. /// </summary>
  12. public class JsonHandler : IHttpHandler
  13. {
  14. public void ProcessRequest(HttpContext context)
  15. {
  16. context.Response.ContentType = "text/javascript";
  17. DataTable table = SqlHelper.ExecuteDataset(SqlHelper.connectionString, CommandType.Text, "select Id, title, content from Accordion").Tables[0];
  18. context.Response.Write(JSONHelper.DataTableToJSON(table));
  19. }
  20. public bool IsReusable
  21. {
  22. get
  23. {
  24. return false;
  25. }
  26. }
  27. }
  28. }
Copyright © Linux教程網 All Rights Reserved