asp.net下 jquery jason 高效传输数据
程序员文章站
2024-03-11 10:14:49
default.html
default.html
<!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 src="js/jquery-1.2.6.js" type="text/javascript"></script>
<script src="js/gonneng.js" type="text/javascript"></script>
<script src="js/ajaxfn.js" type="text/javascript"></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">
订购日期
</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>
handler.ashx
<%@ 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
{
string dbfile = configurationmanager.appsettings["conn"].tostring();
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";
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()
{
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;
}
}
}
}
ajaxfn.js
//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+"> 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";
}
}
gonneng.js
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);
});
});
还需要jquery-1.2.6.js 网上很多
web.config 中添加
<appsettings>
<add key="conn" value="server=.;database=northwind;uid=sa;pwd=sa"/>
<add key="pagesize" value="10"/>
</appsettings>
<!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 src="js/jquery-1.2.6.js" type="text/javascript"></script>
<script src="js/gonneng.js" type="text/javascript"></script>
<script src="js/ajaxfn.js" type="text/javascript"></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">
订购日期
</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>
handler.ashx
<%@ 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
{
string dbfile = configurationmanager.appsettings["conn"].tostring();
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";
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()
{
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;
}
}
}
}
ajaxfn.js
//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+"> 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";
}
}
gonneng.js
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);
});
});
还需要jquery-1.2.6.js 网上很多
web.config 中添加
<appsettings>
<add key="conn" value="server=.;database=northwind;uid=sa;pwd=sa"/>
<add key="pagesize" value="10"/>
</appsettings>
上一篇: Swift洗牌动画效果的实现方法
下一篇: xml 文件的创建和读取代码