国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

實(shí)例講解jquery與json的結(jié)合

2019-11-20 10:50:33
字體:
供稿:網(wǎng)友

通過AJAX異步減少網(wǎng)絡(luò)內(nèi)容傳輸,而JSON則可以把傳輸內(nèi)容縮減到純數(shù)據(jù);然后利用jQuery內(nèi)置的AJAX功能直接獲得JSON格式的數(shù)據(jù);在客戶端直接綁定到數(shù)據(jù)控件里面,從而達(dá)到最優(yōu)。
1.設(shè)計(jì)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=" >> " />  <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"> 訂購(gòu)日期 </span>/ <span id="ShippedDate"> 發(fā)貨日期 </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屬性比較重要,用于數(shù)據(jù)綁定。

2.使用jQuery編寫AJAX請(qǐng)求文件

 var pageIndex = 1 var pageCount = 0;  $(function(){ GetPageCount();//取得分頁總數(shù) pageCount = parseInt($("#pagecount").val());//分頁總數(shù)放到變量pageCount里 $("#load").hide();//隱藏loading提示 $("#template").hide();//隱藏模板 ChangeState(0,1);//設(shè)置翻頁按鈕的初始狀態(tài)  bind();//綁定第一頁的數(shù)據(jù)  //第一頁按鈕click事件 $("#first").click(function(){ pageIndex = 1; ChangeState(0,1); bind(); });  //上一頁按鈕click事件 $("#previous").click(function(){ pageIndex -= 1; ChangeState(-1,1); if(pageIndex <= 1) { pageIndex = 1; ChangeState(0,-1); } bind(); });  //下一頁按鈕click事件 $("#next").click(function(){ pageIndex += 1; ChangeState(1,-1); if(pageIndex>=pageCount) { pageIndex = pageCount; ChangeState(-1,0); } bind(pageIndex); });  //最后一頁按鈕click事件 $("#last").click(function(){ pageIndex = pageCount; ChangeState(1,0); bind(pageIndex); }); });  //AJAX方法取得數(shù)據(jù)并顯示到頁面上 function bind() { $("[@id=ready]").remove(); $("#load").show(); $.ajax({ type: "get",//使用get方法訪問后臺(tái) dataType: "json",//返回json格式的數(shù)據(jù) url: "Handler.ashx",//要訪問的后臺(tái)地址 data: "pageIndex=" + pageIndex,//要發(fā)送的數(shù)據(jù) complete :function(){$("#load").hide();},//AJAX請(qǐng)求完成時(shí)隱藏loading提示 success: function(msg){//msg為返回的數(shù)據(jù),在這里做數(shù)據(jù)綁定 var data = msg.table; $.each(data, function(i, n){ var row = $("#template").clone(); row.find("#OrderID").text(n.OrderID); row.find("#CustomerID").text(n.CustomerID); row.find("#EmployeeID").text(n.EmployeeID); row.find("#OrderDate").text(ChangeDate(n.OrderDate)); if(n.RequiredDate !== undefined) row.find("#ShippedDate").text(ChangeDate(n.RequiredDate)); row.find("#ShippedName").text(n.ShipName); row.find("#ShippedAddress").text(n.ShipAddress); row.find("#ShippedCity").text(n.ShipCity); row.find("#more").html("<a href=OrderInfo.aspx?id=" + n.OrderID + "&pageindex="+pageIndex+"> More</a>"); row.attr("id","ready");//改變綁定好數(shù)據(jù)的行的id row.appendTo("#datas");//添加到模板的容器中 }); $("[@id=ready]").show(); SetPageInfo(); } }); }  function ChangeDate(date) { return date.replace("-","/").replace("-","/"); }  //設(shè)置第幾頁/共幾頁的信息 function SetPageInfo() { $("#pageinfo").html(pageIndex + "/" + pageCount); }  //AJAX方法取得分頁總數(shù) function GetPageCount() { $.ajax({ type: "get", dataType: "text", url: "Handler.ashx", data: "getPageCount=1", async: false, success: function(msg){ $("#pagecount").val(msg); } }); }  //改變翻頁按鈕狀態(tài) function ChangeState(state1,state2) { if(state1 == 1) { document.getElementById("first").disabled = ""; document.getElementById("previous").disabled = ""; } else if(state1 == 0) { document.getElementById("first").disabled = "disabled"; document.getElementById("previous").disabled = "disabled"; } if(state2 == 1) { document.getElementById("next").disabled = ""; document.getElementById("last").disabled = ""; } else if(state2 == 0) { document.getElementById("next").disabled = "disabled"; document.getElementById("last").disabled = "disabled"; } } 

3.利用JSON三方控件在服務(wù)器端獲取JSON格式數(shù)據(jù) 

<%@ WebHandler Language="C#" Class="jQueryJSON.Handler" %>  using System; using System.Data; using System.Web; using System.Collections; using System.Web.Services; using System.Web.Services.Protocols; using System.Configuration; using System.Data.SqlClient; using System.Text; using System.Xml; using NetServ.Net.Json;  namespace jQueryJSON { /// <summary> /// $codebehindclassname$ 的摘要說明 /// </summary> [WebService(Namespace = "http://tempuri.org/json/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] public class Handler : IHttpHandler { readonly int PageSize = int.Parse(ConfigurationManager.AppSettings["PageSize"]); public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; //不讓瀏覽器緩存 context.Response.Buffer = true; context.Response.ExpiresAbsolute = DateTime.Now.AddDays(-1); context.Response.AddHeader("pragma", "no-cache"); context.Response.AddHeader("cache-control", ""); context.Response.CacheControl = "no-cache";  string result = ""; if (context.Request.Params["getPageCount"] != null) result = GetPageCount(); if (context.Request.Params["pageIndex"] != null) { string pageindex = context.Request.Params["pageIndex"]; //if (context.Cache.Get(pageindex) != null) // result = context.Cache.Get(pageindex).ToString(); //else //{ // result = GetPageData(context.Request.Params["pageIndex"]); // context.Cache.Add( // pageindex, // result, // null, // DateTime.Now.AddMinutes(1), // System.Web.Caching.Cache.NoSlidingExpiration, // System.Web.Caching.CacheItemPriority.Default, // null); //} result = GetPageData(context.Request.Params["pageIndex"]); } context.Response.Write(result); }  private string GetPageData(string p) { int PageIndex = int.Parse(p); string sql; if (PageIndex == 1) sql = "select top " + PageSize.ToString() + " * from Orders order by OrderID desc"; else 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"; string dbfile = ConfigurationManager.ConnectionStrings["conn"].ToString(); SqlConnection conn = new SqlConnection(dbfile); SqlDataAdapter da = new SqlDataAdapter(sql, conn); DataTable dt = new DataTable("table"); da.Fill(dt); return DataTableJson(dt);  }  private string GetPageCount() { string dbfile = ConfigurationManager.ConnectionStrings["conn"].ToString(); SqlConnection conn = new SqlConnection(dbfile); SqlCommand cmd = new SqlCommand("select count(*) from Orders", conn); conn.Open(); int rowcount = Convert.ToInt32(cmd.ExecuteScalar()); conn.Close(); return ((rowcount + PageSize - 1) / PageSize).ToString(); }  private string DataTable2Json(DataTable dt) { StringBuilder jsonBuilder = new StringBuilder(); jsonBuilder.Append("{/""); jsonBuilder.Append(dt.TableName); jsonBuilder.Append("/":["); for (int i = 0; i < dt.Rows.Count; i++) { jsonBuilder.Append("{"); for (int j = 0; j < dt.Columns.Count; j++) { jsonBuilder.Append("/""); jsonBuilder.Append(dt.Columns[j].ColumnName); jsonBuilder.Append("/":/""); jsonBuilder.Append(dt.Rows[i][j].ToString()); jsonBuilder.Append("/","); } jsonBuilder.Remove(jsonBuilder.Length - 1, 1); jsonBuilder.Append("},"); } jsonBuilder.Remove(jsonBuilder.Length - 1, 1); jsonBuilder.Append("]"); jsonBuilder.Append("}"); return jsonBuilder.ToString(); }  private string DataTableJson(DataTable dt) { JsonWriter writer = new JsonWriter(); JsonObject content = new JsonObject(); JsonArray Orders = new JsonArray(); JsonObject Order; JsonObject OrderItem = new JsonObject();  for (int i = 0; i < dt.Rows.Count; i++) { Order = new JsonObject(); for(int j =0;j<dt.Columns.Count;j++) { Order.Add(dt.Columns[j].ColumnName, dt.Rows[i][j].ToString()); } Orders.Add(Order); } content.Add(dt.TableName, Orders); content.Write(writer);  writer = new IndentedJsonWriter(); content.Write(writer);  return writer.ToString(); }  public bool IsReusable { get { return false; } } } }

以上就是jquery與json的結(jié)合實(shí)例講解,希望對(duì)大家充分學(xué)習(xí)jquery與json的結(jié)合相關(guān)文章有所幫助。

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 赫章县| 葫芦岛市| 泰和县| 陵川县| 陆良县| 墨江| 白玉县| 兰考县| 伊吾县| 高安市| 荥经县| 焉耆| 凯里市| 福清市| 呼图壁县| 土默特右旗| 大洼县| 木里| 监利县| 池州市| 西吉县| 平果县| 开鲁县| 炎陵县| 图片| 淄博市| 沂源县| 峨眉山市| 沾化县| 岗巴县| 崇礼县| 苏州市| 永吉县| 新绛县| 铜山县| 陕西省| 绩溪县| 新建县| 中阳县| 犍为县| 集贤县|