我想在我的 JavaScript 应用程序中使用历史记录状态。
这个 JSFiddle 示例 https://jsfiddle.net/xyft1pfa/单击链接时将 URL 更改为这些值:
- /第1页/
- /第2页/
- /第3页/
我的问题是,如果我直接在浏览器中访问这些 URL,我将如何从我的应用程序中加载这些 URL 内容?
目前,如果我这样做,它显然会尝试在服务器上找到要加载的页面/端点,但该页面/端点不存在。
单击链接加载第 3 页会将 URL 更新为 /page-3/
但如果我手动将 /page-3/
加载到该地址中bar 它会加载 404 缺失页面,因为文件不存在。我想找到一种方法,让它加载我的单页 JS 应用程序,并在以任何方式访问该 URL 时加载该页面上的正确内容。
我没有使用框架。
// this should be the Ajax Method.
// and load the url content
var setCurrentPage = function(url) {
$('h2 span').html(url || "/");
$("#menu-nav a[href='" + url + "']").fadeTo(500, 0.3);
};
$('#menu-nav a').click(function(e) {
e.preventDefault();
var targetUrl = $(this).attr('href'),
targetTitle = $(this).attr('title');
$("#menu-nav a[href='" + window.location.pathname + "']").fadeTo(500, 1.0);
window.history.pushState({
url: "" + targetUrl + ""
}, targetTitle, targetUrl);
setCurrentPage(targetUrl);
});
window.onpopstate = function(e) {
$("#menu-nav a").fadeTo('fast', 1.0);
setCurrentPage(e.state ? e.state.url : null);
};
HTML
<h2>Current Page: <span>/</span></h2>
<ul id="menu-nav">
<li><a href="/page-1/" title="Pagina 1">Page 1</a></li>
<li><a href="/page-2/" title="Pagina 2">Page 2</a></li>
<li><a href="/page-3/" title="Pagina 3">Page 3</a></li>
</ul>
最佳答案
在setCurrentPage中通过ajax请求从服务器加载页面数据:
var serverBase = "http://example.com/getPage?page=";
var setCurrentPage = function(url) {
$.getJSON(serverBase + url, function(json){
$('h2 span').html(json.html);
$("#menu-nav a[href='" + url + "']").fadeTo(500, 0.3);
});
};
服务器可以通过 json 响应:
{"html": "<div>got from the server</div>"}
您需要根据服务器的预期设置正确的 URL。
您可能还会得到一些关于如何使用单页网站位置的 #hash 的想法:您可能还可以看看这个想法:https://github.com/browserstate/history.js/wiki/Intelligent-State-Handling
关于javascript - 如何使用浏览器历史记录状态在我的单页 JavaScript 应用程序中加载 URL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35048249/