首页 技术 正文
技术 2022年11月17日
0 收藏 928 点赞 3,902 浏览 1236 个字

以往用Ajax来实现无刷新分页,用户一按F5,页数就记不住了,点了一个链接也是同一个问题,再想回退回来,就回到第一页了。上次看到一篇文章,说到window.location.hash的用途,于是萌生了这么一个想法,把这个用来保存Ajax的状态。

大概的实现思路是这样的:页面监听window.onhashchange事件,然后通过Ajax向后台请求分页内容,再替换掉原来的分页结果。当然这个方法要一开始也执行一下,用来应对回退功能。

代码大概如下:

@{
ViewBag.Title = "Index";
}<h2>Index</h2>
<div id="MainDiv"></div>@section scripts{
<script>
function GoToPage(PageIndex) {
$.ajax({
url: '@Url.Action("GetPage")',
data: { Page: PageIndex },
success: function (data) {
$("#MainDiv").html(data);
}
});
} function GetLocationHash() {
//var IsGotoPage = false;
var PageIndex = 1;
var m = window.location.hash.slice(1).split("&");
for (var i = 0; i < m.length; i++) {
var item = m[i];
if (item.indexOf("Page=") > -1) {
PageIndex = item.slice(5);
}
}
GoToPage(PageIndex);
//alert(values);
}
window.onhashchange = GetLocationHash;
GetLocationHash();
</script>
}

Index.cshtml

@model IEnumerable<dynamic>
<table>
<thead>
<tr>
<th>编号</th>
<th>内容</th>
<th>日期</th>
<th>操作</th>
</tr>
</thead>
@foreach (var item in Model)
{
<tr>
<td>
@item.ID
</td>
<td>
@item.Content
</td>
<td>
@item.UpdateDate
</td>
<td>
@Html.ActionLink("查看", "Detail", new { ID = item.ID })
</td>
</tr>
}
</table>
<ul>
@for (int i = 1; i <= ViewBag.PageCount; i++)
{
if (i == ViewBag.PageIndex)
{
<li style="display: inline-block"><span>@i</span></li>
}
else
{
<li style="display: inline-block"><a href="#Page=@i" rel="external nofollow" >@i</a></li>
} }
</ul>

GetPage.cshtml

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,492
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,907
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,740
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,495
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,132
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,297