我想在我的JavaScript应用程序中使用历史状态。
此JSFiddle示例https://jsfiddle.net/xyft1pfa/在单击链接时将URL更改为这些值:
我的问题是,如果我在浏览器中直接访问这些URL,我将如何从我的应用程序中生成这些URL的加载内容?
目前,如果我这样做,它显然会尝试在服务器上找到不存在的页面/端点。
单击load 3的链接将更新到/page-3/的/page-3/,但是如果我要手动将/page-3/加载到地址栏中,它将加载一个丢失的404页,因为文件不存在。我想找出一种方法,让它加载我的单一页面,JS应用程序,并加载正确的内容时,该网址是以任何方式访问。
我不是在使用框架。
// 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>发布于 2016-01-27 22:17:23
在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。
您可能还会得到一些关于如何使用单页网站位置的#散列的一些想法:您可能还会看到这个想法:https://github.com/browserstate/history.js/wiki/Intelligent-State-Handling。
https://stackoverflow.com/questions/35048249
复制相似问题