Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the history improvement ajax list for h5

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

Today, I will talk to you about the history of h5 to improve what the ajax list is. Maybe many people don't know much about it. In order to let everyone know more, Xiaobian summarizes the following contents for everyone. I hope everyone can gain something according to this article.

Information-rich websites are usually displayed in pagination. When clicking "Next Page," many websites adopt a dynamic request method to avoid page refresh. Although everyone is ajax, but from some small details or can distinguish between good and bad. A small detail is whether browsers can support the "back" and "forward" buttons. This article discusses two ways to make the browser go back and forward, or to make ajax have the ability to go back and forward to the previous page just like redirecting to a new page.

The simplest way to achieve pagination is to add several pages after the URL, click "Next Page" and redirect the page to the new address of page+1. For example, Sina's news website does this by changing the URL: index_1, index_2, index_3... But if this list is not part of the main body of the page, or if other parts of the page have a lot of rich elements such as images, such as navigation is a large slider, then the whole page will flicker badly and many resources will have to be reloaded. So use Ajax requests to dynamically change DOM.

However, ordinary dynamic requests do not change the URL. When the user clicks on the next page, or clicks on the first page, he may click on the browser's return key when he wants to return to the previous page, which leads to the return time not to return to the original page, but to the previous URL. For example, CCTV's news network is like this. Let's start with ajax requests and analyze them with a complete case.

I made a demo.

First, write a request:

//var pageIndex = 0; //request function makeRequest(pageIndex){ var request = new XMLHttpRequest(); request.onreadystatechange = stateChange; //Request two parameters, one is the current page number, the other is the number of data per page request.open("GET", "/getBook? page=" + pageIndex + "&limit=4", true); request.send(null); function stateChange(){ //status code 4, means loaded, request completed if(request.readyState !== 4 ){ return; } //Request successful if(request.status >= 200 && request.status

< 300 || request.status === 304){ var books = JSON.parse(request.responseText); renderPage(books); } } } 拿到数据后进行渲染: function renderPage(books){ var bookHtml = "" + " " + " 书名" + " 作者" + " 版本" + " "; for(var i in books){ bookHtml += "" + " " + books[i].book_name + "" + " " + books[i].author + "" + " " + books[i].edition + "" + ""; } bookHtml += ""; bookHtml += "上一页" + "下一页"; var section = document.createElement("section"); section.innerHtml = bookHtml; document.getElementById("book").appendChild(section); } 这样一个基本的ajax请求就搭起来了,然后再响应"下一页"按钮: function nextPage(){ //将页面的index加1 pageIndex++; //重新发请求和页面加载 makeRequest(pageIndex); } 到此,如果不做任何处理的话,就不能够发挥浏览器返回、前进按钮的作用。 如果能够检测用户点了后退、前进按钮的话,就可以做些文章。h6就是增加了这么一个事件_window.onpopstate,当用户点击那两个按钮就会触 发这个事件。但是光检测到这个事件是不够的,还得能够传些参数,也就是说返回到之前那个页面的时候得知道那个页面的pageIndex。通过 history的pushState方法可以达到这个目的,pushState(pageIndex)将当前页的pageIndex存起来,再返回到这个 页面时获取到这个pageIndex。pushState的参数如下: 复制代码 代码如下: window.history.pushState(state, title, url); 其中state为一个object{},用来存放当前页面的数据,title标题没有多大的作用,url为当前页面的url,一旦更改了这个url,浏览器地址栏的地址也会跟着变化。 于是,在请求下一页数据的nextPage函数里面,加多一步操作: function nextPage(){ pageIndex++; makeRequest(pageIndex); //存放当前页面的数据 window.history.pushState({page: pageIndex}, null, _window.location.href); } 然后监听popstate事件: //如果用户点击返回或者前进按钮 window.addEventListener("popstate", function(event){ var page = 0; //由于第一页没有pushState,所以返回到第一页的时候是没有数据的,因此得做下判断 if(event.state !== null){ page = event.state.page; } makeRequest(page); pageIndex = page; }); state数据通过event传进来,这样就可以得到pageIndex。 但是,这样实现还有问题,在第二页的时候如果刷新页面的话,会发生错乱,如下所示:首先点下一页到第二页,然后刷新页面,出现第一页,再点下一页,出现第二页,点返回时出现问题,显示还是第二页,不是期望的第一页,直到再次点返回时才是第一页: 从右边的工具栏可以发现,点第一次返回的时候获取到的pageIndex仍然是1。对于这种情况,需要分析history模型,如下所示: 可以理解为对history的操作,浏览器有一个队列,用来存放访问的记录,包括每个访问的网址还有state数据。一开始,队列的首指针指向page = 0的位置,点下一页时,执行了pushState,在这个队列插入了一个元素,同时通过pushState操作记录了这个元素的url和state数据。 在这里可以看出,pushState的操作最重要的作用还是给history队列插入元素,这样浏览器的后退按钮才不是置灰的状态,其次才是上面说的存放 数据。点后退的时候,队首指针后退一步指向page = 0的位置,点前进时又前进指向page = 1的位置。 如果在page = 1的位置刷新页面,模型是这个样子的: 在第2步刷新的时候,页面的pageIndex又恢复成默认值0,所以page = 0,显示第一页数据,但是history所用的队列并没有改变。然后再点下一页时,又给这个队列push了一个元素,这个队列就有两个pageIndex 为1的元素,所以必须得两次返回才能回到page = 0的位置,也就是上面说的错乱的情况。 根据上面的分析,这样的实现是有问题的,一但用户不是在page = 0的位置刷新页面,就会出现需要点多次返回按钮才能够回到原先的页面。 所以得在刷新的时候,把当前页的state数据更新一下,用replaceState,替换队列队首指针的数据,也就是当前页的数据。方法是页面初始化时replace一下: window.history.replaceState({page: pageIndex /*此处为0*/}, null, _window.location.href); 这样模型就变成:

However, when refreshing, users prefer to display the current page instead of returning to the first page. One solution is to use the window.history.state data for the current page, a property that browsers later supported. When setting pageIndex during page initialization, it takes from history.state:

var pageIndex = window.history.state === null ? 0 : window.history.state.page;

The history.state in safari is the data passed in by the most recent pushState execution, so this method works in chrome/firefox, but safari does not work.

The second option is to store the current number of pages with localStorage in h6:

//page initialization, take the current page number first from localStorage var pageIndex = window.localStorage.pageIndex|| 0; function nextPage(){ //Add 1 to the index of the page and store it in localStorage window.localStorage.pageIndex = ++pageIndex; //reissue request and page load makeRequest(pageIndex); window.history.pushState({page: pageIndex}, null, _window.location.href); } window.addEventListener("popstate", function(event){ var page = 0; if(event.state !== null){ page = event.state.page; } makeRequest(page); //Click Back or Forward to place the page in localStorage window.localStorage.pageIndex = page; });

Place all changes to pageIndex in localStorage. When you refresh the page, you can retrieve the pageIndex of the current page.

The above method is to put pageIndex in the state parameter, there is a way to put it in the third parameter url, that is, by changing the current page URL method. pageIndex from the URL:

//Current Page var pageIndex = _window.location.search.replace("? page=", "") || ; function nextPage(){ //add index to page ++pageIndex; //reissue request and page load makeRequest(pageIndex); window.history.pushState(null, null, "? page=" + pageIndex); }

Note that once the pushState on line 8 is executed, the address of the current URL changes.

One thing to note is that although window.history.length returns the number of elements in the current queue of yes, it does not mean that history itself is that queue. Output for history[i] by different browsers:

You can see that history is an array, and its role is to let the user get history.length, the current length, but the filling content is uncertain.

In addition to using history, there is also a hash method, Netease News is using such a method:

//Current Page var pageIndex = _window.location.hash.replace("#page=", "") || ; function nextPage(){ makeRequest(pageIndex); _window.location.hash = "#page=" + pageIndex; } window.addEventListener("hashchange", function(){ var page = _window.location.hash.replace("#page=", "") || ; makeRequest(page); });

For support, refer to caniuse website: history IE10 and above support, hashchange support is better, IE8 and above are supported.

Although hashchange is better supported, history has the advantage of being able to transfer data. For some complex applications, it may be very useful, and history supports back/go operations.

After reading the above, do you have any further understanding of what h5's history improves ajax list? If you still want to know more knowledge or related content, please pay attention to the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report