Examples of jquery and json integration, examples of jqueryjson
AJAX reduces network content transmission asynchronously, while JSON reduces the transmitted content to pure data. Then, jQuery's built-in AJAX function is used to directly obtain data in JSON format; bind the client directly to the data control to achieve optimal performance.
1. design the htm page
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2. Use jQuery to compile the AJAX request file
Var pageIndex = 1 var pageCount = 0; $ (function () {GetPageCount (); // retrieve the total number of pageCount = parseInt ($ ("# pagecount "). val (); // put the total number of pages into the variable pageCount $ ("# load "). hide (); // hide the loading prompt $ ("# template "). hide (); // hide the template ChangeState (); // set the initial state bind () of the flip button (); // bind data on the first page // click Event on the first page $ ("# first "). click (function () {pageIndex = 1; ChangeState (0, 1); bind () ;}); // click Event on the previous page $ ("# previous "). click (function () {pageIndex-= 1; ChangeState (-); if (pageIndex <= 1) {pageIndex = 1; ChangeState (0,-1);} bind ();}); // next page button click event $ ("# next "). click (function () {pageIndex + = 1; ChangeState (1,-1); if (pageIndex> = pageCount) {pageIndex = pageCount; ChangeState (-1, 0 );} bind (pageIndex) ;}); // click Event on the last page $ ("# last "). click (function () {pageIndex = pageCount; ChangeState (); bind (pageIndex) ;}); // The AJAX method retrieves data and displays the functio on the page. N bind () {$ ("[@ id = ready]"). remove (); $ ("# load "). show (); $. ajax ({type: "get", // use the get method to access the background dataType: "json", // return the json format Data url: "Handler. ashx ", // the backend address to be accessed data:" pageIndex = "+ pageIndex, // The data to be sent complete: function () {$ (" # load "). hide () ;}, // when the AJAX request is complete, hide the loading prompt success: function (msg) {// msg as the returned data. Bind var data = msg here. table; $. each (data, function (I, n) {var row = $ ("# template "). clone (); row. find ("# Or DerID "). 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" pai.html ("<a href = OrderInfo. aspx? Id = "+ n. orderID + "& pageindex =" + pageIndex + "> More </a>"); row. attr ("id", "ready"); // Changes the id row of the row bound to the data. appendTo ("# datas"); // Add to the container of the template}); $ ("[@ id = ready]"). show (); SetPageInfo () ;}}) ;}function ChangeDate (date) {return date. replace ("-","/"). replace ("-", "/");} // sets the page number/page number. function SetPageInfo () {$ ("# pageinfo" ).html (pageIndex + "/" + pageCount);} // obtain the total number of pages using the AJAX method function GetPageCount () {$. ajax ({type: "get", dataType: "text", url: "Handler. ashx ", data:" getPageCount = 1 ", async: false, success: function (msg) {$ (" # pagecount "). val (msg) ;}}) ;}// 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. Use the JSON third-party control to obtain JSON-format data on the server side
<% @ 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 $ abstract description /// </summary> [WebService (Namespace = "http://tempuri.org/json/")] [WebServiceBinding (ConformsTo = WsiProfiles. basicProfile1_1)] public class Handler: IHttpHandler {readonly int PageSize = int. parse (ConfigurationManager. deleetask[ "PageSize"]); public void ProcessRequest (HttpContext context) {context. response. contentType = "text/plain"; // do not allow the browser to cache context. response. buffer = true; context. response. expiresAbso Lute = 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 ;}}}}
The above is an example of the combination of jquery and json. It is helpful for you to fully learn about the combination of jquery and json.
Articles you may be interested in:
- JQuery submits data to Webservice in combination with Json, and receives Json data returned from Webservice.
- Jquery-based text box and autocomplete (asp.net + json)
- Examples of jQuery and getJson usage