【问题标题】:Ajax back button functionalityAjax 后退按钮功能
【发布时间】:2016-05-29 17:51:36
【问题描述】:

我不知道如何使用 historyAPI 或 history.js 请帮助!我的代码是这样的……

我想要的是显示一组按钮,用户单击其中一个,然后显示另一组按钮,并在第一组之间进行 ajax 调用,通过使用 css 隐藏...

$(".button1").click(function(){
    $('#div2').css("display","none");
    $('#div1').css("display","none");
    val1 = $(this).attr("value");
    query = 'phone.php?val1='+val1;
    myQuery();
    $('#div2').css("display","block");
});

$(".button2").click(function(){
    val2= $(this).attr("value");
    $("#div2").css("display","none");
    query = 'phone.php?val1='+val1+'&val2='+val2;
    myQuery();
   $("#div3").css("display","block");
});

function myQuery() {
    if (window.XMLHttpRequest) {
        xmlHttp = new XMLHttpRequest();
    } else {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlHttp.onreadystatechange = function(){
        if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
        document.getElementById("sql").innerHTML = xmlHttp.responseText;
    }
}

xmlHttp.open('GET', query, true);
xmlHttp.send();
}

当我按下后退按钮时,它会转到上一个网站......所以我当然希望它显示第一组按钮并显示更新前的内容。

【问题讨论】:

    标签: javascript php jquery ajax history.js


    【解决方案1】:

    使用 Ajax 时,您不会在浏览器历史记录中添加任何内容,这就是为什么当您按下后退按钮时,您会返回到上一个记录的页面。 如果您希望记录您的 Ajax 调用,就像您要进入一个新页面一样,您需要在历史堆栈中推送一个新状态。

    if ( typeof(window.history.pushState) == 'function' ) {
        var stateObj ={
            title: title,
            url: query,
        } ;
        window.history.pushState (stateObj, title, query) ;     
    }
    

    您还需要实现一个 onpopstate 事件函数,以根据用户返回历史记录后变为活动的状态来隐藏/显示您的按钮。

    window.onpopstate =function (event) {
        alert ("location: " + document.location + ", state: " + JSON.stringify (event.state)) ;
        // based on the event.state values, restore buttons visibility here...
    
    } ;
    

    【讨论】:

    • 那么我到底应该在哪里调用 pushState 函数和 onpopstate
    • 我会把它放在你的'myQuery'函数上。您决定是仅在成功查询时执行此操作,还是始终根据您的业务逻辑执行此操作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-05
    • 1970-01-01
    • 1970-01-01
    • 2014-11-21
    • 2018-06-09
    相关资源
    最近更新 更多