您现在的位置: 365建站网 > 365文章 > jquery和json的结合

jquery和json的结合

文章来源:365jz.com     点击数:241    更新时间:2009-10-04 11:13   参与评论

    通过AJAX异步减少网络内容传输,而JSON则可以把传输内容缩减到纯数据;然后利用jQuery内置的AJAX功能直接获得JSON格式的数据;在客户端直接绑定到数据控件里面,从而达到最优。

   1.设计htm页面: 

</>code

    1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
    2. <html xmlns="http://www.w3.org/1999/xhtml"> 
    3. <head> 
    4. <title>test2</title> 
    5. <script language="javascript" type="text/javascript" src="js/jquery-latest.pack.js"></script> 
    6. <script language="javascript" type="text/javascript" src="js/PageDate.js"></script> 
    7.  
    8. </head> 
    9. <body> 
    10. <div> 
    11. <div> 
    12. <br /> 
    13. <input id="first" type="button" value=" << " /><input id="previous" type="button" 
    14. value=" < " /><input id="next" type="button" value=" > " /><input id="last" type="button" 
    15. value=" >> " /> 
    16. &nbsp;<span id="pageinfo"></span> 
    17. <ul id="datas"> 
    18. <li id="template"> 
    19. <span id="OrderID"> 
    20. 订单ID  
    21. </span>/  
    22. <span id="CustomerID"> 
    23. 客户ID  
    24. </span> 
    25. <span id="EmployeeID"> 
    26. 雇员ID  
    27. </span>/  
    28. <span id="OrderDate"> 
    29. 订购日期  
    30. </span>/  
    31. <span id="ShippedDate"> 
    32. 发货日期  
    33. </span>/  
    34. <span id="ShippedName"> 
    35. 货主名称  
    36. </span>/  
    37. <span id="ShippedAddress"> 
    38. 货主地址  
    39. </span>/  
    40. <span id="ShippedCity"> 
    41. 货主城市  
    42. </span>/  
    43. <span id="more"> 
    44. 更多信息  
    45. </span> 
    46. </li> 
    47. </ul> 
    48. </div> 
    49. <div id="load" style="left: 0px; position: absolute; top: 0px; background-color: red"> 
    50. LOADING....  
    51. </div> 
    52. <input type="hidden" id="pagecount" /> 
    53. </div> 
    54. </body> 
    55. </html> 

注:ID属性比较重要,用于数据绑定。

2.使用jQuery编写AJAX请求文件

</>code

    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. }  

3.利用JSON三方控件在服务器端获取JSON格式数据

</>code

    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. }  

如对本文有疑问,请提交到交流论坛,广大热心网友会为你解答!! 点击进入论坛

发表评论 (241人查看0条评论)
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
昵称:
最新评论
------分隔线----------------------------

快速入口

· 365软件
· 杰创官网
· 建站工具
· 网站大全

其它栏目

· 建站教程
· 365学习

业务咨询

· 技术支持
· 服务时间:9:00-18:00
365建站网二维码

Powered by 365建站网 RSS地图 HTML地图

copyright © 2013-2024 版权所有 鄂ICP备17013400号