保留浏览器“后退”使用 AJAX/jQuery 加载页面和 History.pushState() 方法的按钮功能
我想在通过 AJAX(jQuery load
方法)加载页面并通过 history.pushState
方法将 URL 推送到浏览器栏时保留后退按钮功能。当单击浏览器后退按钮并且第一次单击仅恢复上一个 URL 但不加载上一个页面时,就会出现此问题。
到目前为止,这是我的代码:
$(function(){
var profile_url= "/profile";
$('#click_button').click(function(){
$('#main_content').load(profile_url);
history.pushState({profile:profile_info}, "profile", profile_url);
});
});
我的问题是,有什么方法可以在第一次单击后退按钮时将上一页 AJAX 加载到 #main_content
div 中?
任何帮助/建议将不胜感激。
I'd like to preserve the back button functionality when loading pages via AJAX (jQuery load
method) and pushing the URL to the browser bar via the history.pushState
method. The problem occurs when one clicks on the browser back button and the 1st click only restores the previous URL but does not load the previous page.
Here's my code so far:
$(function(){
var profile_url= "/profile";
$('#click_button').click(function(){
$('#main_content').load(profile_url);
history.pushState({profile:profile_info}, "profile", profile_url);
});
});
My question is is there any way to do an AJAX load of the previous page into the #main_content
div on the 1st click of the back button?
Any help/advice would be greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我想引导大家使用一个名为 PJAX 的 jQuery 插件,它完成了我最终有兴趣提出这个问题的任务。 Pjax() 结合了 jQuery AJAX 和 PushState,用于页面加载和保存浏览器历史记录。
这是代码,这是
pjax()
的精彩演示。它真的很棒并且易于使用,在演示中,只需记住单击有助于演示
pjax()
功能的复选框即可。I'd like to direct everyone to a jQuery plugin called PJAX which accomplishes what I was ultimately interested in asking this question. Pjax() combines jQuery AJAX and pushState for page loading and preserving browser history.
Here's the code, and here's a nice demo of
pjax()
in action.It is really great and easy to use, in the demo, just remember to click the checkbox which is there to help demonstrate
pjax()
's functionality.为此,您需要订阅“popstate”事件。
可以这样做:
For this you need to subscribe to the 'popstate' event.
You could do this like this:
您可以使用
popstate
事件来实现此目的。请参阅https://developer.mozilla.org/en/DOM/window.onpopstate 了解详情。另请查看 History.js,它提供了一个包装器,并且可以回退到 url 主题标签,以防万一浏览器不支持历史API。
You can use the
popstate
event for this purpose. See https://developer.mozilla.org/en/DOM/window.onpopstate for details.Also have a look at History.js which provides a wrapper and can fallback to url hashtags in case the browser does not support the history api.