让我的后退和前进按钮与ajax一起工作

时间:2013-05-17 23:29:42

标签: javascript jquery ajax

由于我精心修改了一些代码,我的网站工作得更快,但如果浏览器的后退/前进按钮有效,我会很高兴。现在,使用下面的代码,浏览器地址栏永远不会改变。当有人点击“返回”时,会将其从应用程序中删除。

是否可以通过任何简单的方式更改此设置,以便浏览器的后退/前进按钮有效?否则,如果有人能指出我正确的方向。谢谢你的帮助。

$(document).on("ready", function () {

    //I want to load content into the '.page-content' class, with ajax

    var ajax_loaded = (function (response) {

        $(".page-content")

        .html($(response).filter(".page-content"));

        $(".page-content .ajax").on("click", ajax_load);


    });



    //the function below is called by links that are described 
    //with the class 'ajax', or are in the div 'menu' 

    var history = [];

    var ajax_load = (function (e) {

        e.preventDefault();


        history.push(this);
        var url = $(this).attr("href");
        var method = $(this).attr("data-method");


        $.ajax({
            url: url,
            type: method,
            success: ajax_loaded
        });

    });


    //monitor for clicks from menu div, or with
    //the ajax class
    //why the trigger?

    $("#menu a").on("click", ajax_load);
    $(".ajax").on("click", ajax_load);
    $("#menu a.main").trigger("click");



});

3 个答案:

答案 0 :(得分:1)

这是一种检测你问的方式。

忍受我的后退和前进按钮是一项冒险的任务。

window.onload = function () {

    if (typeof history.pushState === "function") {

        history.pushState("someState", null, null);

        window.onpopstate = function () {

            history.pushState("newState", null, null);

            // Handle the back (or forward) buttons here
            // Will not handle refresh, use onbeforeunload for this.
        };
    }
}

答案 1 :(得分:1)

您可以使用jquery地址插件(http://www.asual.com/jquery/address/)。 它有一个事件,可以检测用户何时按下后退/前进按钮。

$.address.externalChange(function() { console.log('back/forward pressed'); });

据我所知,没有办法区分后退和前锋。

答案 2 :(得分:0)

你一定要检查History.js 这是一些示例代码: -

  (function(window,undefined){

    // Prepare
    var History = window.History; // Note: We are using a capital H instead of a lower h
    if ( !History.enabled ) {
         // History.js is disabled for this browser.
         // This is because we can optionally choose to support HTML4 browsers or not.
        return false;
    }

    // Bind to StateChange Event
    History.Adapter.bind(window,'statechange',function(){ // Note: We are using statechange instead of popstate
      var State = History.getState(); // Note: We are using History.getState() instead of event.state
      //History.log(State.data, State.title, State.url);
      var goto_url = State.url;            
      $.ajax({
          url: goto_url,
          dataType: "script"
      });
    });
  })(window);