如何将当前页面推送到浏览器历史记录

Bin*_*hen 5 javascript ajax jquery

我有一个页面,用户可以使用输入来过滤结果.将一些字符输入到输入条目后,而不是手动删除它,人们喜欢在浏览器中使用后退按钮返回输入的"空"状态.

但是结果是由AJAX提取的,这意味着后退按钮的行为是错误的(无法清除输入条目,只是返回上一页),是否可以将空的或当前的URL推送到后端堆栈中以便用户可以得到他们想要的结果吗?

要清楚,我想要:

1) user enter some characters to the input entry
2) user press "filter" button
3) user press back button
4) the input entry is cleared
Run Code Online (Sandbox Code Playgroud)

kyb*_*kos 2

以下是管理历史的两种一般方法。尽管您可能需要调整代码,但它们都可以使用“空白页”的想法。

执行此操作的两种方法使用片段标识符或新的历史 API。

使用片段标识符看起来像这样:

<body onhashchange="hashChanged()" onload="hashChanged()">

<input id='query'></input><button onclick="location.hash = '#'+document.getElementById('query').value">Query</button>

<script type="text/javascript">

function query(str) {
    // do your ajaxy thing
}

function hashChanged() {
    var str = location.hash.substring(1);
    document.getElementById('query').value = str;
    query(str);
}

</script>
</body>
Run Code Online (Sandbox Code Playgroud)

该技术适用于 ie8、firefox 3.6 和 chrome 5。您可以通过隐藏滚动区域并检测滚动,或者定期轮询位置的哈希部分,将类似的东西侵入到早期的浏览器中。

另一种方法使用新的历史 API

<body onload="queryChanged();">

<input id='query'></input><button onclick="history.pushState(str, "", "?query="+str);query(document.getElementById('query').value)">Query</button>

<script type="text/javascript">

function query(str) {
    // do your ajaxy thing
}

function queryChanged() {
    var str = "";
    var re = /[\?|&]query=([^&]*)/
    if (re.test(location.search)) {
        str = re.exec(location.search)[1];
    }
    document.getElementById('query').value = str;
    query(str);
}

window.onpopstate = queryChanged;
</script>
</body>
Run Code Online (Sandbox Code Playgroud)

这适用于最近的 firefox 和 chrome,但仅适用于 ie10。

当然,您可能最好使用图书馆。一个旧的插件是Very Simple History,但是还有更现代的 jquery 插件提供类似的功能,例如BBQhashchange 插件