Solve the Problem of page rollback and refresh in the Ajax framework.

Source: Internet
Author: User

Solve the Problem of page rollback and refresh in the Ajax framework.
Problems

If you use Firefox or other browsers to access the RMS website, we may find that the switching between pages is throughAJAXThe URL of the page is not changed at the same time.AJAXAsynchronous requests implement rollback and refresh, but they are not supported for browser forward and backward requests. The page will be returned to the initial welcome page after each refresh and rollback.AJAXIt can achieve partial page refresh, which can achieve very good data loading effect and bring a very good user experience,AJAXYou cannot keep records in your browser's historical sessions. When you open a page,AJAXVarious data loading methods are fast. For example, a list page can be loaded asynchronously to flip pages. However, if you accidentally refresh the page, you have to re-calculate the page number, once the user changes the session Status (Browser forward, backward, and refresh ),AJAXData is lost.



TraditionalAJAXThe following problems exist:

1. You can refresh the page content, but cannot change the page URL.

2. You cannot directly access a module of the system through a website.

3. Developers must be the first to roll back and refresh. This increases the workload for developers and does not meet user habits.

4. the browser then introduces the onhashchange interface. Unsupported browsers can only regularly determine whether the hash is changed.

5. However, this method is unfriendly to search engines.



Use Technology

To solve the problems brought about by traditional ajax, HTML5 introduces a new API, namely: history. pushState, history. replaceState

You can use the pushState and replaceState interfaces to operate the browser history and change the URL of the current page.

PushState adds the specified URL to the browser history. replaceState replaces the current URL with the specified URL.

History. pushState (state, title, url)

Add the current URL and history. state to history and add the new state and URL to the current state. Does not cause page refresh.

State: the status information corresponding to the URL to jump.

Title: The title ).

Url: the URL to jump to. It cannot be cross-origin.

History. replaceState (state, title, url)

The history. replaceState () operation is similar to history. pushState (). The difference is that the replaceState () method modifies the current historical record entries rather than creating new ones.

State: the status information corresponding to the URL to jump.

Title: The title ).

Url: the URL to jump to. It cannot be cross-origin.



AddEventListener (type, listener)

AddEventListener is a function that listens for events and processes them.

Type: the type of the event.

Listener: a function that listens to post-event events. This function must accept the Event object as its unique parameter and cannot return any results.



Solution



BecauseAJAXWithout changing the page content, the page URL remains unchanged. to distinguish different content on the page, you must first redefine the URL of each page, because the RMS website is mostly used $. for post asynchronous requests, we can use URLs to record the parameters (request addresses and transmission parameters) of the post request. When the browser refresh and roll back the request, THE post request is automatically sent based on the URL record information to enter the corresponding page to implement the desired function.



DefinitionURLSyntax:

For example, "http: // localhost/rms_hold/index. php/Home/Index/loadHomePage #/rms_hold/index. php/Home/ResourceRequest/getRequestPage @ apply_type = 1 & resource_name = ADM_BIZCARD! 1"



"Http: // localhost/rms_hold/index. php/Home/Index/loadHomePage "is the URL of the original page. If you perform any operations on the RMS website before the problem is solved, the website will not change. Now we use "#" to separate the URL. "#" is followed by the recorded ajax request "/rms_hold/index. php/Home/ResourceRequest/getRequestPage is the request address, which is separated by "#" and "@", while "@" and "!" This is the parameters of the sending request address. "apply_type = 1" and "resource_name = ADM_BIZCARD" are separated.



Refresh and rollback listening:

if (history.pushState) {window.addEventListener("popstate", function() {back_ajax_mod_url();back_ajax_post();if(location.href.indexOf("#")==-1){window.location.reload();}});back_ajax_mod_url();back_ajax_post();}




As shown in the code above, the window object provides the onpopstate event. You can use the addEventListener method to listen to the onpopstate event. Every time the URL is rolled back by the browserBack_ajax_mod_url ()AndBack_ajax_post ()Function, and when the browser refreshes, according to the return value of history. pushState is not emptyBack_ajax_mod_url ()AndBack_ajax_post ()Function.



External interface:



function back_ajax_mod_url(){var url_ajax=ajaxback_url.pop();var title ="Home | UniqueSoft RMS";if(url_ajax){history.pushState({ title: title }, title,location.href.split("#")[0] + "#"+ url_ajax);}}



IntroductionBack_ajax_mod_url ()Function, which is used to form an external interface with the array ajaxback_url. ajaxback_url is a global array used to store the URL that needs to be added to history.Back_ajax_mod_url ()The function adds the current URL and history. state to history without page refreshing.



$("#reportTable tbody").on("click", "trtd img[alt = 'Detail']",function() {var id = $(this).attr("business_leave_id");$.post("__MODULE__/ReportCenter/getReportDetailPage",{"report_name": "ADM_TRAVEL_REP","item_id": id,},function(data) {ajaxback_url.push("__MODULE__/ReportCenter/getReportDetailPage"+ "@" + "item_id=" + id + "&" +"report_name=ADM_TRAVEL_REP");$("#container").html(data);back_ajax_mod_url();});});




The above function isAJAXAsynchronous request events will cause no changes to the page. The bold part is the external interface we provide, after using this interface, a new URL will be generated in history to record the post method that reaches the page.



URLResolution processor:



As shown in the following functionBack_ajax_post ()Is the URL Parsing processor of the RMS system. Based on the URL syntax mentioned earlier, readAJAXRequest, and automatically sendAJAXRequest to obtain the required page

function back_ajax_post() {if (location.href.indexOf("#")!= -1) {var post_href =location.href.split("#")[1];if (location.href.indexOf("@")!= -1) {var post_url =post_href.split("@")[0];var post_params =post_href.split("@")[1];if(post_params.indexOf("!") != -1) {var post_page_index =post_params.split("!")[1];post_params =post_params.split("!")[0];};} else {var post_url = post_href;var post_params = "";var post_page_index = "";}var get_resource_href =location.href;if(get_resource_href.indexOf("!") != -1) {get_resource_href =get_resource_href.split("!")[0];};if(get_resource_href.indexOf("resource_name=") != -1) {var has_resource_name =get_resource_href.split("resource_name=")[1];var siderbar_index =has_resource_name;} else if(get_resource_href.indexOf("report_name=") != -1) {var has_resource_name =get_resource_href.split("report_name=")[1];var siderbar_index =has_resource_name.split("_REP")[0];};if (!post_page_index ||$("#personalInfo").length <= 0) {if (!post_url) {window.location.href ="__MODULE__";}$.ajax({type: "post",url: post_url,data: post_params,success: function(res){$('#pageContainer').html(res);if(post_page_index) {location.href= location.href.split("!")[0] + "!1";} else {location.href= location.href.split("!")[0];};},error: function(res) {window.location.href = "__MODULE__";},});}//for request page next&backif (post_page_index) {var previous_index =$(".navbar,.steps .navbar-innerul.row-fluid").find("li.active").find(".number").text();var differ =post_page_index - previous_index;lock_for_req_back_next =1;if (differ > 0) {for (var i = 0; i <differ; i++) {$("#personalInfo").trigger("click");};} else {differ = -differ;for (var i = 0; i <differ; i++) {$("#btn_back").trigger("click");};};lock_for_req_back_next =0;}//for side barif (siderbar_index =="IT_TESTMACHINE" || siderbar_index == "IT_LAPTOP"|| siderbar_index == "IT_OTHER_RESOURCE") {siderbar_index ="IT_RESOURCE";}$("ul.page-sidebar-menuli ul.sub-menu li a").each(function() {var resource_name =$(this).attr("href").split("resource_name=")[1];if (siderbar_index ==resource_name) {$('.page-sidebarul').children('li.active').removeClass('active');$('.page-sidebarul').children('arrow.open').removeClass('open');$(this).parents('li').each(function() {$(this).addClass('active');$(this).children('a > span.arrow').addClass('open');$(this).parents('.sub-menu').show();});$(this).parent('li').parents('li').addClass('active open');return false;} else {$('.sub-menu').hide();}});$("ul.page-sidebar-menuli").not(".open").find("ul").hide();}}



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.