简单ajax分页 jQuery实现动态创建Dom
//前台aspx代码:
<script type="text/javascript" src="Scripts/jquery-1.4.1-vsdoc.js"></script>
<script type="text/javascript">
var $table = $("<table border='1px' width='1000px'></table>");
$(function () {
var pageIndex = 1;
changeImg(pageIndex);
})
function changeImg(pageIndex) {
//调用前对其内容进行清空
$table.text("");
//getJSON 实现
$.getJSON("Wolf.ashx?pageIndex=" + pageIndex, function (data) {
//获得数据总数 来判断 是否 上一页 下一页
var pageCount = parseInt(data[data.length - 1]);
//在div下进行附加 动态创建table
$("#d").append($table);
var $tr = $("<tr></tr>");
for (var i = 0; i < data.length - 1; i++) {
var $td = $("<td><img width='300px' height='300px' src='" + data[i] + "'/></td>");
$tr.append($td);
$table.append($tr);
}
var $page = $("<tr></tr>");
$td = $("<td><a id ='up' href='#'>上一页</a></td>");
$page.append($td);
$td = $("<td></td>");
$page.append($td);
$td = $("<td><a id='down' href='#'>下一页</a></td>");
$page.append($td);
$table.append($page);
$("#down").click(function () {
//判断是否越界 对其禁用
if (pageIndex + 1 >= 10) {
$(this).attr("disabled", true);
}
else {
pageIndex++;
changeImg(pageIndex);
}
})
$("#up").click(function () {
//判断是否越界 对其禁用
if (pageIndex - 1 <= 0) {
$(this).attr("disabled", true);
} else {
pageIndex--;
changeImg(pageIndex);
}
});
})
}
//后台ashx代码:
</script>
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/json";
//获取wolf文件夹的绝对路径
string path = context.Request.MapPath("Wolf");
//获取所有图片
string[] files = System.IO.Directory.GetFiles(path, "*.jpg", System.IO.SearchOption.AllDirectories);
//获取发送过来的请求 页面索引
string pageIndex = context.Request.QueryString["pageIndex"];
//每页显示的图片个数
int size = 3;
//默认 页面的显示索引 为 第一页
int index = 1;
//对其 索引转换,若转换失败,则为默认 页面1
if (int.TryParse(pageIndex,out index))
{
}
//用来响应 存储 数据
List<string> filepath = new List<string>();
//1 3*1 1 2 3
//2 3*2 4 5 6
for (int i = 0; i < files.Length; i++)
{
//这里需要判断每次是发送不同的 3条数据
if (i < index * size&&i>=(index-1)*size)
{
filepath.Add(files[i]);
}
}
//规律: 0,1,2, 3,4,5, 6,7,8, 9,10,11;
// Index 1 i<(1*3) 0,1,2
// Index 2 i<(2*3) 3,4,5
// 思路:
// 1>要想每次都显示3个,在之间还需要加上if过滤条件,因为i的值是"<"而产生不需要的值,
// 那么需要在进行过滤的i一定是">"某个值;
// 2>每次相差的数是size,那可能就是size乘以某个数;size又是不变的,
// 所以size与某个数相乘 则决定了最终值;那个数起决定性作用,刚好乘以 (index-1)则刚好就是慢一拍的那个数。
//求出总共页面数,用来返值 ,对 请求超出页面索引 判断使用
int pageCount= files.Length / 3 + 1;
//对泛型 进行序列化 json对象
JavaScriptSerializer ser = new JavaScriptSerializer();
string strfile = ser.Serialize(filepath);
//替换 ] 存储 总页面数
strfile = strfile.Replace("]",","+ pageCount.ToString()+"]");
//响应
context.Response.Write(strfile);
}

浙公网安备 33010602011771号