Solution to the problem of the Ajax fallback refresh page

Source: Internet
Author: User

In the script home to see an article, I think it may be used later, but can not be collected, so it can only be transferred to the blog park. The following is the original address: http://www.jb51.net/article/87856.htm This article mainly introduces the Ajax fallback Refresh page problem solution of the relevant information, very good, with reference value, interested friends learn together

Introduction to Ajax:

Ajax, "Asynchronous JavaScript and XML" (Asynchronous JavaScript and XML), refers to a web development technique that creates interactive Web applications.

AJAX = Asynchronous JavaScript and XML (a subset of standard generic markup languages).

AJAX is a technique for creating fast, Dynamic Web pages.

AJAX enables Web pages to be updated asynchronously by exchanging small amounts of data in the background with the server. This means that you can update a part of a webpage without reloading the entire page.

Traditional Web pages (without AJAX) if you need to update the content, you must reload the entire page page.

There is a problem

If you use a browser such as Firefox to access the RMS site, we may find that the switch between pages is implemented through Ajax asynchronous request, and the URL of the page will not change, although you can through the page button through the Ajax asynchronous request to implement a fallback refresh, However, for the browser forward and backward cannot support, each time after refreshing and back, the page will be back to the beginning of the Welcome page. Ajax can achieve a partial refresh of the page, you can do very good data loading effect, give users a very good experience, but Ajax can not keep records in the history of the browser, when you click on a page, Ajax various data loading is very fast, such as a list page can be loaded with asynchronous to page, But if the user accidentally refreshes the page, then the page number will have to restart the calculation, once the user changed the session state (browser forward, back, refresh), then Ajax will lose the relevant data.

Traditional Ajax has the following problems:

1, can change the page content without refresh, but cannot change the page URL

2, can not support direct access to the system through the URL of a module, you must go through the tap operation

3, fallback, refresh must be a developer of their own first, both to increase the workload of developers, and do not conform to user habits

4, and then the browser introduced Onhashchange interface, not supported by the browser can only be timed to determine whether the hash changes

5, but this way is very unfriendly to search engines

Use of technology

In order to solve the problems caused by traditional Ajax, HTML5 introduced a new API, namely: History.pushstate,history.replacestate

The browser history can be manipulated via the pushstate and Replacestate interfaces, and the URL of the current page is changed.

Pushstate is to add the specified URL to the browser history, Replacestate replaces the specified URL with the current URL.

History.pushstate (state, title, URL)

Joins the current URL and history.state to the history and adds the new state and URL to the current. does not cause page refreshes.

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

Title: Caption (now ignored, not processed).

URL: The URL address to jump to, not across domains.

History.replacestate (state, title, URL)

The History.replacestate () operation is similar to History.pushstate (), except that the Replacestate () method modifies the current history entry instead of creating a new entry.

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

Title: Caption (now ignored, not processed).

URL: The URL address to jump to, not across domains.

AddEventListener (type, listener)
AddEventListener is a listener event and handles the corresponding function.

Type: the kind of event.

Listener: A function that handles events after hearing an event. This function must accept the event object as its only argument, and it cannot return any results.

Workaround

Since Ajax does not refresh the content of the page, so the URL of the page is always constant, in order to distinguish the different content on the page, first need to redefine the URL of each page, because the RMS site uses $.post asynchronous request, We can use the URL to record the various parameters of the POST request (request address, delivery parameters), when the browser to refresh, fallback operation, according to the information recorded by the URL automatically send a POST request, into the corresponding page, so as to achieve the desired function.

Define URL Syntax:

The following address has been taken as an example:

"Http://localhost/rms_hold/index.php/home/index/loadhomepage#/rms_hold/index.php/home/resourcerequest/[email Protected]_type=1&resource_name=adm_bizcard!1 "

"Http://localhost/rms_hold/index.php/Home/Index/loadHomePage" is the URL of the original page, and there will be no changes to the URL if you do anything on the RMS website before the problem is resolved. Now we use "#" to split the URL, "#" followed by the Ajax request we recorded "/rms_hold/index.php/home/resourcerequest/getrequestpage" is the requested address, it is "#" and "@" split, And at "@" and "! "Between this is the various parameters sent to the request address," apply_type=1 "and" Resource_name=adm_bizcard "are divided by" & ".

Refresh, fallback listener processing:

if (history.pushstate) {Window.addeventlistener(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 preceding code, the Onpopstate event is provided on the Window object, and the AddEventListener method can be used to listen for the Onpopstate event whenever the URL is given a URL because the browser fallback is Back_ajax_mod_url () and Back_ajax_post () function parsing, processing, and when the browser refreshes, according to the History.pushstate return value is not empty, will still be the resulting URL in Back_ajax_mod_url () and Back_ajax_post () function for parsing and processing.

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);}}

Introduce the Back_ajax_mod_url () function, which is an external interface to the array ajaxback_url, Ajaxback_url is a global array for the URLs that need to be added to the history, and then by Back_ajax_mod_ The URL () function adds the current URL and history.state to the history without a page refresh.

 $ ("#reportTable tbody"). On ("click", "trtd img[alt = ' Detail ']" ,  function   () { var  id = $ (this ). attr ("business_leave_id"  "__module__/reportcenter/getreportdetailpage" ,{ "report_name": "Adm_ Travel_rep " "item_id" : ID,},  function   "__module__/ Reportcenter/getreportdetailpage "+" @ "+" item_id= "+ ID +" & "+" Report_name=adm_travel_rep " #container"  

The above function is an AJAX asynchronous request event in the RMS system, which causes the page to change without flushing, and the bold part is the external interface we provide, and after using the interface, a new URL is generated in the history to record the Post method that reached the page.

URL Resolution Processor:

As shown in the following function, Back_ajax_post () is the URL resolution processor for the RMS system, reads the AJAX request to change the content on the page according to the URL syntax mentioned earlier, and automatically sends an AJAX request to get the desired page

functionBack_ajax_post () {if(Location.href.indexOf ("#")! =-1) {varPost_href =location.href.split ("#") [1];if(Location.href.indexOf ("@")! =-1) {varPost_url =post_href.split ("@") [0];varPost_params =post_href.split ("@") [1];if(Post_params.indexof ("!")!! =-1) {varPost_page_index =post_params.split ("!") [1];p ost_params=post_params.split ("!") [0];};} Else {varPost_url =Post_href;varPost_params = "";varPost_page_index = "";}varGet_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) {varHas_resource_name =get_resource_href.split ("resource_name=") [1];varSiderbar_index =Has_resource_name;} Else if(Get_resource_href.indexof ("report_name=")! =-1) {varHas_resource_name =get_resource_href.split ("report_name=") [1];varSiderbar_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) {varPrevious_index =$ (". Navbar,.steps. Navbar-innerul.row-fluid"). Find ("Li.active"). Find (". Number")). text ();varDiffer =post_page_index-Previous_index;lock_for_req_back_next=1;if(Differ > 0) { for(vari = 0; I <differ; A= "" bar= "" differ= "-differ;"Else="" for= "" i= "0;"if= "li=" "lock_for_req_back_next=" 0; "Resource_name=" $ (this). attr ("href"). Split ("Resource_name=") [1]; "Side=" " siderbar_index= "=" ul.page-sidebar-menuli= "" ul.sub-menu= ""var= "" > 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 ();}} </differ;>

The above is a small series to introduce you to the Ajax Fallback Refresh page solution of the relevant knowledge, I hope that we have some help, if you have any questions please give me a message, small series will promptly reply to you. Thank you very much for the support of the Scripting House website!

Solution to the problem of the Ajax fallback refresh page

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.