您的位置:首页 > Web前端 > JQuery

jquery跨域获取数据以及分页

2011-01-19 17:37 295 查看
今天做了一个jquery跨域获取josn数据的功能,同时对获取的数据进行分页。看代码:

html 代码:

代码

<%@ WebHandler Language="C#" Class="GetpfData" %>

using System;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Text;

public class GetpfData : IHttpHandler {

public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
string hid = context.Request["hid"].ToString();
string hname =HttpUtility.UrlDecode(context.Request["hName"].ToString());
int num=Convert.ToInt32(context.Request["pagenum"].ToString());
int page=Convert.ToInt32(context.Request["p"].ToString());

SqlParameter[] paremeter = {
new SqlParameter("@hid",SqlDbType.Int)
};
paremeter[0].Value = hid;
int id = (int)SqlHelper.ExecuteScalar(CommandType.Text, "select ID from Hero where hid=@hid",paremeter);
int count = (int)SqlHelper.ExecuteScalar("select count(*) from Skin where Name=" + id);//查询总记录数;
//查询要显示的数据;
string sql = "select top " + num + " * from Skin where Name="+id+" and id not in(select top " + num * (page-1) + " id from Skin where Name="+id+" order by id desc) order by id desc";
DataSet ds = SqlHelper.ExecuteDataset(sql);
//构造json格式;
StringBuilder sb = new StringBuilder();
sb.Append("[");
for (int i = 0; i <ds.Tables[0].Rows.Count; i++)
{
sb.Append("{");
sb.AppendFormat("'ID':'{0}','title':'{1}','title1':'{2}','pic':'{3}','score':'{4}','hname':'{5}','page':'{6}'", ds.Tables[0].Rows[i]["id"].ToString(), ds.Tables[0].Rows[i]["SkinTitle"].ToString().Length > 9 ? StringHelper.GetLeftStr(ds.Tables[0].Rows[i]["SkinTitle"].ToString(), 9) : ds.Tables[0].Rows[i]["SkinTitle"].ToString(), ds.Tables[0].Rows[i]["SkinTitle"].ToString(), ds.Tables[0].Rows[i]["Skinpic"].ToString(), ds.Tables[0].Rows[i]["Score"].ToString(), hname, page);
sb.Append("}");
if (i < ds.Tables[0].Rows.Count - 1)
{
sb.Append(",");
}
}
sb.Append("]");
string data = sb.ToString();
string callback = context.Request.QueryString["jsoncallback"];
data = "{d:" + data + ",count:" + count + "}";
context.Response.Write(callback+"("+data+")");
context.Response.End();
}
public bool IsReusable {
get {
return false;
}
}

}
思路很简单,就是每次查询给后台传入要查询的差数,再把Response.Write()出来的数据进行重新的展示。

这样做有很大问题的,如果访问量非常大的话,服务器会受不了的。解决方法:

1、加上缓存。

2、将要查询的json数据生成js文件,从js文件查询需要的数据。(但这样数据的实时更新就不行了的)。

对要处理的数据更新是很快情况下建议选择第二种方法是很不错的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: