Ajax load and click browser back button to go back

origin

When developing an application system, especially a background management system, every time you refresh all the pages, it wastes traffic, consumes server resources, and makes the interface flash, and the user experience is not good. This is why Ajax is used.

After using Ajax, I found that using the browser's back button does not work. This is very inconvenient, which requires the use of the history function provided by html5.

ideas

ajax loading

This is very simple with jquery, see the code

$("#mycontent").load(url);

This loads the html fragment in the url into the div with the id mycontent.

How to let history know that a new page is loaded

use

history.pushState(state,title,url)。

You can see that there are three parameters, the first parameter stores some custom information, such as the url of the ajax block. The second parameter is useless.

The third parameter affects the url displayed in the browser's address bar. This url can be processed so that the user can correctly enter the ajax page when he clicks the refresh browser button.
Like the method I use

http://127.0.0.1:1985/?child=/case/list?type=flfg&title=%E6%B3%95%E8%A7%84%E5%88%97%E8%A1%A8

The child parameter is the url that the ajax page needs to load, so that the home page loads it when it finds the child parameter.
write picture description here

How to know that the user clicked back

When the user hits the back button, the popstate event is fired. In this event, the url is read from the state and loaded into the DIV.

Which a tags to bind

Not all hyperlinks need to be displayed in a div. At this time, a selector needs to be added. The method I use is to add a class to the a tag.
Some children's shoes like to use "#hahadiv a".

How to make a connection in a web page loaded with ajax in a div continue to load with ajax

How the connection in the list like in the image above is still displayed in the div after being clicked.
Method: In the callback of the load function, add the binding function and call.

How to bind a dynamically generated connection such as jquery datatable

After the connection is dynamically generated, the binding function is called. In the following example, the binding function is bindDivA.
Code example after datatable drawing is completed

        table.on( 'draw', function () {
            console.log( 'Redraw occurred at: '+new Date().getTime() );
            bindDivA();
        } );

Off topic jquery datatable how to save state

This is a good space, it has stateSave function.

        var table = $('#example2').DataTable( {
            "processing": true,
            "serverSide": true,
            "ajax": {
                "url": "/case/listJSON?type=${type}",
                "type": "POST"
            },
            "columns": [
                {'data': 'id'},
                {'data': 'title'},
                {'data': 'type'},
                {'data': 'qi'},
                {'data': 'addtm'},
                {'data': 'cat'},
            ],
            "columnDefs": [ {
                "targets": 1,
                "data": "title",
                "render": function ( data, type, row, meta ) {
                    //console.log(row);
                    var id = row["id"];
                    return  "<a class='inframe' href='/case/one?id={0}'>{1}</a>".format(""+id,data);
                }
            } ],
            stateSave: true,
            stateSaveCallback: function(settings,data) {
                localStorage.setItem( 'clist_DataTables_' + settings.sInstance, JSON.stringify(data) )
            },
            stateLoadCallback: function(settings) {
                return JSON.parse( localStorage.getItem( 'clist_DataTables_' + settings.sInstance ) )
            }
        } );

A pit I fell into while writing

When I first started debugging, I found that some can be rolled back and some cannot be rolled back. I checked and found that the click function forgot to write return false;
as a result, clicking a connection is equivalent to pushingState twice. One is written by our code, and the other is pushed by the browser itself.
Of course, there is no state parameter when the browser itself pushes, so hehe.

code directly

//--------------------  历史管理 -----------------------------------
function loadToDiv(url,title,usePush){
    $("#mycontent").load(url,function (e) {
        bindDivA();
    });
    if(title){
        $("#contentHeader").html(title);
    }
    var state = { 'pageurl':url,'pagetitle':title};

    if(usePush){
        console.log("push state of "+state);
        history.pushState(state, title, "/?child="+url+"&title="+$("#contentHeader").text());
    }
}
function bindDivA(){
    console.log("bindInframeA called");
    $(".inframe").bind("click",function(e){
        //var href = this.href;
        var href  = $(this).attr("href");
        var title = $(this).text();
        console.log("visit href "+href);
        loadToDiv(href,title,true);
        return false;
    });
}
 $(document).ready(function(){
     bindDivA();
 });
if (history.pushState) {
    window.addEventListener("popstate", function() {
        console.log("popstate called ,href="+location.href +", state = "+history.state);
        if(! history.state) return;
        console.log(history.state);
        loadToDiv(history.state.pageurl,history.state.pagetitle,false);
    });
}
//--------------------  历史管理 结束 -----------------------------------

I don't want to understand, how to use it easily?

1 Write this code into your own js file and reference it in the page.
2 Write a div with an id of mycontent to load ajax content
3 Add class=”inframe” to the link that needs to be loaded in the div

ok.

refer to

[1] http://www.zhangxinxu.com/wordpress/2013/06/html5-history-api-pushstate-replacestate-ajax/comment-page-1/#comment-382378

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325518332&siteId=291194637