以往用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

相关文章:

  • 2021-10-24
  • 2022-12-23
  • 2021-04-16
  • 2022-12-23
  • 2021-09-28
  • 2022-12-23
  • 2021-11-22
猜你喜欢
  • 2022-02-06
  • 2022-12-23
  • 2022-12-23
  • 2022-01-21
  • 2022-12-23
  • 2021-06-26
  • 2021-12-15
相关资源
相似解决方案