实例讲解jquery与json的结合

 更新时间:2016年01月07日 16:19:40   投稿:lijiao  
这篇文章主要介绍了jquery与json的结合,分为三个阶段,设计htm页面,使用jQuery编写AJAX请求文件,感兴趣的小伙伴们可以参考一下

通过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请求文件

 var pageIndex = 1 
var pageCount = 0; 
 
$(function(){ 
GetPageCount();//取得分页总数 
pageCount = parseInt($("#pagecount").val());//分页总数放到变量pageCount里 
$("#load").hide();//隐藏loading提示 
$("#template").hide();//隐藏模板 
ChangeState(0,1);//设置翻页按钮的初始状态 
 
bind();//绑定第一页的数据 
 
//第一页按钮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方法取得数据并显示到页面上 
function bind() 
{ 
$("[@id=ready]").remove(); 
$("#load").show(); 
$.ajax({ 
type: "get",//使用get方法访问后台 
dataType: "json",//返回json格式的数据 
url: "Handler.ashx",//要访问的后台地址 
data: "pageIndex=" + pageIndex,//要发送的数据 
complete :function(){$("#load").hide();},//AJAX请求完成时隐藏loading提示 
success: function(msg){//msg为返回的数据,在这里做数据绑定 
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");//改变绑定好数据的行的id 
row.appendTo("#datas");//添加到模板的容器中 
}); 
$("[@id=ready]").show(); 
SetPageInfo(); 
} 
}); 
} 
 
function ChangeDate(date) 
{ 
return date.replace("-","/").replace("-","/"); 
} 
 
//设置第几页/共几页的信息 
function SetPageInfo() 
{ 
$("#pageinfo").html(pageIndex + "/" + pageCount); 
} 
 
//AJAX方法取得分页总数 
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.利用JSON三方控件在服务器端获取JSON格式数据 

<%@ 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的结合实例讲解,希望对大家充分学习jquery与json的结合相关文章有所帮助。

相关文章

  • jquery单选框radio绑定click事件实现方法

    jquery单选框radio绑定click事件实现方法

    这篇文章主要介绍了jquery单选框radio绑定click事件实现方法,可实现针对单选框radio值的改变作出响应,非常具有实用价值,需要的朋友可以参考下
    2015-01-01
  • jQuery Mobile页面跳转后未加载外部JS原因分析及解决

    jQuery Mobile页面跳转后未加载外部JS原因分析及解决

    Web开发进行页面跳转时在pageB中引用的JS并未成功运行,针对这个问题本文给予了详细的解决方法,感兴趣的你可以参考下哈,希望可以帮助到你
    2013-03-03
  • jQuery利用FormData上传文件实现批量上传

    jQuery利用FormData上传文件实现批量上传

    这篇文章主要为大家详细介绍了jQuery利用FormData上传文件实现批量上传功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-12-12
  • jquery对元素的基本操作实例分析

    jquery对元素的基本操作实例分析

    在本篇文章里小编给大家整理了一篇关于jquery对元素的基本操作实例分析内容,对此有兴趣的朋友们可以跟着学习下。
    2022-01-01
  • jQuery对底部导航进行跳转并高亮显示的实例代码

    jQuery对底部导航进行跳转并高亮显示的实例代码

    这篇文章主要介绍了jQuery对底部导航进行跳转并高亮显示的实例代码,代码简单易懂,非常不错,具有一定的参考借鉴价值 ,需要的朋友可以参考下
    2019-04-04
  • 基于DOM节点删除之empty和remove的区别(详解)

    基于DOM节点删除之empty和remove的区别(详解)

    下面小编就为大家带来一篇基于DOM节点删除之empty和remove的区别(详解)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-09-09
  • 基于jQuery实现的无刷新表格分页实例

    基于jQuery实现的无刷新表格分页实例

    这篇文章主要介绍了基于jQuery实现的无刷新表格分页方法,结合完整实例形式较为详细的分析了jQuery实现无刷新表格分页的具体步骤与相关实现代码,需要的朋友可以参考下
    2016-02-02
  • 初窥JQuery(二) 事件机制(1)

    初窥JQuery(二) 事件机制(1)

    JQuery的事件处理机制在JQuery框架中起着重要的左右,它就像电视机的开关,我们打开电视机的开关才能看到各个电视台精彩的节目,那么我们使用JQuery的事件处理机制就可以创造我们自定义的行为,比如说提交、改变样式、效果显示等等,使我们的网页更加丰富。
    2010-11-11
  • jQuery实现的自定义弹出层效果实例详解

    jQuery实现的自定义弹出层效果实例详解

    这篇文章主要介绍了jQuery实现的自定义弹出层效果,结合实例形式较为详细的分析了jQuery自定义弹出层的布局、事件响应与页面元素动态操作的相关技巧,需要的朋友可以参考下
    2016-09-09
  • Jquery判断IE6等浏览器的代码

    Jquery判断IE6等浏览器的代码

    jquery中利用navigator.userAgent.indexOf来判断浏览器类型,并进行了一下处理,如果不想使用jquery,稍为修改下代码就可以为自己所用
    2011-04-04

最新评论