Examples show the combination of jquery and json

  • 2020-11-20 06:00:21
  • OfStack

AJAX asynchronously reduces the transmission of network content, while JSON reduces the transmission to pure data. Then the data in JSON format is obtained directly by using AJAX function built in jQuery. In the client directly bound to the data control inside, so as to achieve optimal.
1. Design htm page


<!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"> 
 The order ID 
</span>/ 
<span id="CustomerID"> 
 The customer ID 
</span> 
<span id="EmployeeID"> 
 employees ID 
</span>/ 
<span id="OrderDate"> 
 Order date  
</span>/ 
<span id="ShippedDate"> 
 The delivery date  
</span>/ 
<span id="ShippedName"> 
 The shipper name  
</span>/ 
<span id="ShippedAddress"> 
 The shipper address  
</span>/ 
<span id="ShippedCity"> 
 The shipper city  
</span>/ 
<span id="more"> 
 For more information  
</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> 
//// Note: ID Properties are important for data binding. 

2. Use jQuery to write AJAX request files


 var pageIndex = 1 
var pageCount = 0; 
 
$(function(){ 
GetPageCount();// Get the total number of pages  
pageCount = parseInt($("#pagecount").val());// The total number of pages is put into variables pageCount In the  
$("#load").hide();// hidden loading prompt  
$("#template").hide();// Hide the template  
ChangeState(0,1);// Sets the initial state of the page turn button  
 
bind();// Binding is the first 1 Pages of data  
 
// The first 1 Page button click The event  
$("#first").click(function(){ 
pageIndex = 1; 
ChangeState(0,1); 
bind(); 
}); 
 
// on 1 Page button click The event  
$("#previous").click(function(){ 
pageIndex -= 1; 
ChangeState(-1,1); 
if(pageIndex <= 1) 
{ 
pageIndex = 1; 
ChangeState(0,-1); 
} 
bind(); 
}); 
 
// Under the 1 Page button click The event  
$("#next").click(function(){ 
pageIndex += 1; 
ChangeState(1,-1); 
if(pageIndex>=pageCount) 
{ 
pageIndex = pageCount; 
ChangeState(-1,0); 
} 
bind(pageIndex); 
}); 
 
// The last 1 Page button click The event  
$("#last").click(function(){ 
pageIndex = pageCount; 
ChangeState(1,0); 
bind(pageIndex); 
}); 
}); 
 
//AJAX Method takes the data and displays it on the page  
function bind() 
{ 
$("[@id=ready]").remove(); 
$("#load").show(); 
$.ajax({ 
type: "get",// use get Method access background  
dataType: "json",// return json Formatted data  
url: "Handler.ashx",// The background address to access  
data: "pageIndex=" + pageIndex,// The data to be sent  
complete :function(){$("#load").hide();},//AJAX Hidden when the request completes loading prompt  
success: function(msg){//msg For the returned data, do the data binding here  
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+">&nbsp;More</a>"); 
row.attr("id","ready");// Change the row on which the data is bound id 
row.appendTo("#datas");// Add to the container of the template  
}); 
$("[@id=ready]").show(); 
SetPageInfo(); 
} 
}); 
} 
 
function ChangeDate(date) 
{ 
return date.replace("-","/").replace("-","/"); 
} 
 
// Set pages / It's several pages of information  
function SetPageInfo() 
{ 
$("#pageinfo").html(pageIndex + "/" + pageCount); 
} 
 
//AJAX Method gets the total number of pages  
function GetPageCount() 
{ 
$.ajax({ 
type: "get", 
dataType: "text", 
url: "Handler.ashx", 
data: "getPageCount=1", 
async: false, 
success: function(msg){ 
$("#pagecount").val(msg); 
} 
}); 
} 
 
// Change the page turn button state  
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 JSON3 square control to get 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$  Summary description of  
/// </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"; 
// Do not allow the browser to cache  
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; 
} 
} 
} 
}

The above is an example of the combination of jquery and json. I hope it will be helpful for you to fully learn the combination of jquery and json.


Related articles: