我正在使用History.js,我正在尝试获取Google Plus网址的网址。
(function(window, undefined){
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;
}
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);
console.log(State.data.page);
});
$('.item').live('click', function(e){
e.preventDefault();
var url = $(this).children(1).attr('href');
$(document).remove('#content');
$('#loaded').load('/controlpanel' + url + '.php #content');
History.pushState({page: url + '.php'}, "Prova Pagina", History.getRootUrl() + 'controlpanel' + url); // logs {state:1}, "State 1", "?state=1"
});
})(窗口);
当我点击链接时,此脚本有效,但当我手动刷新页面,并且我已经点击链接并且网址变为http://www.mysite.com/something/page时,浏览器会给我一个404错误。 我该如何解决?
的内容答案 0 :(得分:0)
即使JS允许您不重新加载整个页面,仍然可以在服务器端访问URL,以便直接访问该链接的人会看到某些内容(更不用说优雅的降级)。
此外,您必须在锚链接上添加单击处理程序,以便可以阻止默认操作(转到链接)并使用pushState
方法更改URL。像这样:
document.body.onclick = function( e ) {
var evt = e || window.event,
target = evt.target || evt.srcElement // Get the target cross-browser
// If the element clicked is a link
if ( target.nodeName === 'A' ) {
// Use the History API to change the URL
History.pushState() // Use the library correctly
// Don't forget to return false so that the link doesn't make you reload the page
return false
}
}
这绝对不是生产代码(你应该检查外部链接,不要绑定身体等),但是你明白了。