jQuery于json的結合

來源: ajax中國  發布時間: 2009-07-12 22:14  閱讀: 2758 次  推薦: 0   原文鏈接   [收藏]  

通過AJAX異步減少網絡內容傳輸,而JSON則可以把傳輸內容縮減到純數據;然后利用jQuery內置的AJAX功能直接獲得JSON格式的數據;在客戶端直接綁定到數據控件里面,從而達到最優。

1.設計htm頁面:

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
    <html xmlns="http://www.w3.org/1999/xhtml"> 
    <head> 
    <title>test2</title> 
    <script language="javascript" type="text/javascript" src="js/jquery-latest.pack.js"></script> 
    <script language="javascript" type="text/javascript" src="js/PageDate.js"></script> 
     
    </head> 
    <body> 
   <div> 
   <div> 
   <br /> 
   <input id="first" type="button" value=" << " /><input id="previous" type="button" 
   value=" < " /><input id="next" type="button" value=" > " /><input id="last" type="button" 
   value=" >> " /> 
   &nbsp;<span id="pageinfo"></span> 
   <ul id="datas"> 
   <li id="template"> 
   <span id="OrderID"> 
   訂單ID  
   </span>/  
   <span id="CustomerID"> 
   客戶ID  
   </span> 
   <span id="EmployeeID"> 
   雇員ID  
   </span>/  
   <span id="OrderDate"> 
   訂購日期  
   </span>/  
   <span id="ShippedDate"> 
   發貨日期  
   </span>/  
   <span id="ShippedName"> 
   貨主名稱  
   </span>/  
   <span id="ShippedAddress"> 
   貨主地址  
   </span>/  
  <span id="ShippedCity"> 
   貨主城市  
   </span>/  
  <span id="more"> 
   更多信息  
   </span> 
   </li> 
   </ul> 
   </div> 
   <div id="load" style="left: 0px; position: absolute; top: 0px; background-color: red"> 
   LOADING.  
  </div> 
   <input type="hidden" id="pagecount" /> 
   </div> 
  </body> 
  </html> 

 

注:ID屬性比較重要,用于數據綁定。

2.使用jQuery編寫AJAX請求文件

 

   1. var pageIndex = 1 
   2. var pageCount = 0;  
   3.  
   4. $(function(){  
   5. GetPageCount();//取得分頁總數  
   6. pageCount = parseInt($("#pagecount").val());//分頁總數放到變量pageCount里  
   7. $("#load").hide();//隱藏loading提示  
   8. $("#template").hide();//隱藏模板  
   9. ChangeState(0,1);//設置翻頁按鈕的初始狀態  
  10.  
  11. bind();//綁定第一頁的數據  
  12.  
  13. //第一頁按鈕click事件  
  14. $("#first").click(function(){  
  15. pageIndex = 1;  
  16. ChangeState(0,1);  
  17. bind();   
  18. });  
  19.  
  20. //上一頁按鈕click事件  
  21. $("#previous").click(function(){  
  22. pageIndex -= 1;  
  23. ChangeState(-1,1);   
  24. if(pageIndex <= 1)  
  25. {  
  26. pageIndex = 1;  
  27. ChangeState(0,-1);  
  28. }  
  29. bind();   
  30. });  
  31.  
  32. //下一頁按鈕click事件  
  33. $("#next").click(function(){  
  34. pageIndex += 1;  
  35. ChangeState(1,-1);  
  36. if(pageIndex>=pageCount)  
  37. {  
  38. pageIndex = pageCount;  
  39. ChangeState(-1,0);  
  40. }  
  41. bind(pageIndex);   
  42. });  
  43.  
  44. //最后一頁按鈕click事件  
  45. $("#last").click(function(){  
  46. pageIndex = pageCount;  
  47. ChangeState(1,0);  
  48. bind(pageIndex);   
  49. });   
  50. });  
  51.  
  52. //AJAX方法取得數據并顯示到頁面上  
  53. function bind()  
  54. {  
  55. $("[@id=ready]").remove();  
  56. $("#load").show();  
  57. $.ajax({  
  58. type: "get",//使用get方法訪問后臺  
  59. dataType: "json",//返回json格式的數據  
  60. url: "Handler.ashx",//要訪問的后臺地址  
  61. data: "pageIndex=" + pageIndex,//要發送的數據  
  62. complete :function(){$("#load").hide();},//AJAX請求完成時隱藏loading提示  
  63. success: function(msg){//msg為返回的數據,在這里做數據綁定  
  64. var data = msg.table;  
  65. $.each(data, function(i, n){  
  66. var row = $("#template").clone();  
  67. row.find("#OrderID").text(n.OrderID);  
  68. row.find("#CustomerID").text(n.CustomerID);  
  69. row.find("#EmployeeID").text(n.EmployeeID);  
  70. row.find("#OrderDate").text(ChangeDate(n.OrderDate));  
  71. if(n.RequiredDate !== undefined) row.find("#ShippedDate").text(ChangeDate(n.RequiredDate));  
  72. row.find("#ShippedName").text(n.ShipName);  
  73. row.find("#ShippedAddress").text(n.ShipAddress);  
  74. row.find("#ShippedCity").text(n.ShipCity);  
  75. row.find("#more").html("<a href=OrderInfo.aspx?id=" + n.OrderID + "&pageindex="+pageIndex+">&nbsp;More</a>");   
  76. row.attr("id","ready");//改變綁定好數據的行的id  
  77. row.appendTo("#datas");//添加到模板的容器中  
  78. });  
  79. $("[@id=ready]").show();  
  80. SetPageInfo();  
  81. }  
  82. });  
  83. }  
  84.  
  85. function ChangeDate(date)  
  86. {  
  87. return date.replace("-","/").replace("-","/");  
  88. }  
  89.  
  90. //設置第幾頁/共幾頁的信息  
  91. function SetPageInfo()  
  92. {  
  93. $("#pageinfo").html(pageIndex + "/" + pageCount);  
  94. }  
  95.  
  96. //AJAX方法取得分頁總數  
  97. function GetPageCount()  
  98. {  
  99. $.ajax({  
 100. type: "get",  
 101. dataType: "text",  
 102. url: "Handler.ashx",  
 103. data: "getPageCount=1",  
 104. async: false,  
 105. success: function(msg){  
 106. $("#pagecount").val(msg);  
 107. }  
 108. });  
 109. }  
 110.  
 111. //改變翻頁按鈕狀態   
 112. function ChangeState(state1,state2)  
 113. {  
 114. if(state1 == 1)  
 115. {   
 116. document.getElementById("first").disabled = "";  
 117. document.getElementById("previous").disabled = "";  
 118. }  
 119. else if(state1 == 0)  
 120. {   
 121. document.getElementById("first").disabled = "disabled";  
 122. document.getElementById("previous").disabled = "disabled";  
 123. }  
 124. if(state2 == 1)  
 125. {  
 126. document.getElementById("next").disabled = "";  
 127. document.getElementById("last").disabled = "";  
 128. }  
 129. else if(state2 == 0)  
 130. {  
 131. document.getElementById("next").disabled = "disabled";  
 132. document.getElementById("last").disabled = "disabled";  
 133. }  
 134. } 

3.利用JSON三方控件在服務器端獲取JSON格式數據

 

 

   1. <%@ WebHandler Language="C#" Class="jQueryJSON.Handler" %> 
   2.  
   3. using System;  
   4. using System.Data;  
   5. using System.Web;  
   6. using System.Collections;  
   7. using System.Web.Services;  
   8. using System.Web.Services.Protocols;  
   9. using System.Configuration;  
  10. using System.Data.SqlClient;  
  11. using System.Text;  
  12. using System.Xml;  
  13. using NetServ.Net.Json;  
  14.  
  15. namespace jQueryJSON  
  16. {  
  17. /// <summary> 
  18. /// $codebehindclassname$ 的摘要說明  
  19. /// </summary> 
  20. [WebService(Namespace = "http://tempuri.org/json/")]  
  21. [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]  
  22. public class Handler : IHttpHandler  
  23. {  
  24. readonly int PageSize = int.Parse(ConfigurationManager.AppSettings["PageSize"]);  
  25. public void ProcessRequest(HttpContext context)  
  26. {  
  27. context.Response.ContentType = "text/plain";  
  28. //不讓瀏覽器緩存  
  29. context.Response.Buffer = true;  
  30. context.Response.ExpiresAbsolute = DateTime.Now.AddDays(-1);  
  31. context.Response.AddHeader("pragma", "no-cache");  
  32. context.Response.AddHeader("cache-control", "");  
  33. context.Response.CacheControl = "no-cache";  
  34.  
  35. string result = "";  
  36. if (context.Request.Params["getPageCount"] != null) result = GetPageCount();  
  37. if (context.Request.Params["pageIndex"] != null)  
  38. {  
  39. string pageindex = context.Request.Params["pageIndex"];  
  40. //if (context.Cache.Get(pageindex) != null)  
  41. // result = context.Cache.Get(pageindex).ToString();  
  42. //else  
  43. //{  
  44. // result = GetPageData(context.Request.Params["pageIndex"]);  
  45. // context.Cache.Add(  
  46. // pageindex,  
  47. // result,  
  48. // null,  
  49. // DateTime.Now.AddMinutes(1),  
  50. // System.Web.Caching.Cache.NoSlidingExpiration,  
  51. // System.Web.Caching.CacheItemPriority.Default,  
  52. // null);  
  53. //}  
  54. result = GetPageData(context.Request.Params["pageIndex"]);  
  55. }  
  56. context.Response.Write(result);  
  57. }  
  58.  
  59. private string GetPageData(string p)  
  60. {  
  61. int PageIndex = int.Parse(p);  
  62. string sql;  
  63. if (PageIndex == 1)  
  64. sql = "select top " + PageSize.ToString() + " * from Orders order by OrderID desc";  
  65. else  
  66. sql = "select top " + PageSize.ToString() + " * from Orders where OrderID not in(select top " + ((PageIndex - 1) * PageSize).ToString() + " OrderID from Orders order by OrderID desc) order by OrderID desc";  
  67. string dbfile = ConfigurationManager.ConnectionStrings["conn"].ToString();  
  68. SqlConnection conn = new SqlConnection(dbfile);  
  69. SqlDataAdapter da = new SqlDataAdapter(sql, conn);  
  70. DataTable dt = new DataTable("table");  
  71. da.Fill(dt);  
  72. return DataTableJson(dt);  
  73.  
  74. }  
  75.  
  76. private string GetPageCount()  
  77. {  
  78. string dbfile = ConfigurationManager.ConnectionStrings["conn"].ToString();  
  79. SqlConnection conn = new SqlConnection(dbfile);  
  80. SqlCommand cmd = new SqlCommand("select count(*) from Orders", conn);  
  81. conn.Open();  
  82. int rowcount = Convert.ToInt32(cmd.ExecuteScalar());  
  83. conn.Close();  
  84. return ((rowcount + PageSize - 1) / PageSize).ToString();  
  85. }  
  86.  
  87. private string DataTable2Json(DataTable dt)  
  88. {  
  89. StringBuilder jsonBuilder = new StringBuilder();  
  90. jsonBuilder.Append("{\"");  
  91. jsonBuilder.Append(dt.TableName);  
  92. jsonBuilder.Append("\":[");  
  93. for (int i = 0; i < dt.Rows.Count; i++)  
  94. {  
  95. jsonBuilder.Append("{");  
  96. for (int j = 0; j < dt.Columns.Count; j++)  
  97. {  
  98. jsonBuilder.Append("\"");  
  99. jsonBuilder.Append(dt.Columns[j].ColumnName);  
 100. jsonBuilder.Append("\":\"");  
 101. jsonBuilder.Append(dt.Rows[i][j].ToString());  
 102. jsonBuilder.Append("\",");  
 103. }  
 104. jsonBuilder.Remove(jsonBuilder.Length - 1, 1);  
 105. jsonBuilder.Append("},");  
 106. }  
 107. jsonBuilder.Remove(jsonBuilder.Length - 1, 1);  
 108. jsonBuilder.Append("]");  
 109. jsonBuilder.Append("}");  
 110. return jsonBuilder.ToString();  
 111. }  
 112.  
 113. private string DataTableJson(DataTable dt)  
 114. {  
 115. JsonWriter writer = new JsonWriter();  
 116. JsonObject content = new JsonObject();  
 117. JsonArray Orders = new JsonArray();  
 118. JsonObject Order;  
 119. JsonObject OrderItem = new JsonObject();  
 120.  
 121. for (int i = 0; i < dt.Rows.Count; i++)  
 122. {  
 123. Order = new JsonObject();  
 124. for(int j =0;j<dt.Columns.Count;j++)  
 125. {   
 126. Order.Add(dt.Columns[j].ColumnName, dt.Rows[i][j].ToString());  
 127. }  
 128. Orders.Add(Order);   
 129. }   
 130. content.Add(dt.TableName, Orders);  
 131. content.Write(writer);  
 132.  
 133. writer = new IndentedJsonWriter();  
 134. content.Write(writer);  
 135.  
 136. return writer.ToString();  
 137. }  
 138.  
 139. public bool IsReusable  
 140. {  
 141. get  
 142. {  
 143. return false;  
 144. }  
 145. }  
 146. }  
 147. } 

 

0
0
 
 
 

文章列表

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()