您的位置:知识库 » Web前端

jQuery于json的结合

来源: ajax中国  发布时间: 2009-07-12 22:14  阅读: 2810 次  推荐: 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

Web前端热门文章

    Web前端最新文章

      最新新闻

        热门新闻