问题描述
我有一个基于ajax的应用程序,其中我只有一个登录页面和主页.
I have a heavily ajax based application wherein i only have a login page and the main page.
我的大多数链接都是"ajaxed"的,而我的链接是这样的:
Most of my links are "ajaxed" and i have them done like this:
//get the href of the link that has been clicked, ajaxify ANY links
$(document).on('click', '.tree a', function () {
var link = $(this).attr('href'); //get the href off the list
$.ajax({ //ajax request to post the partial View
url: link,
type: 'POST',
cache: false,
success: function (result) {
$('#target').html(result);
$.validator.unobtrusive.parse($("form#ValidateForm"));
}
});
return false; //intercept the link
});
我想在我的应用程序上实现"pushState",到目前为止,我要做的第一步就是添加以下代码:
I want to implement "pushState" on my application and the first step that i have done so far is to add this code:
$(document).on('click', 'a', function () {
history.pushState({}, '', $(this).attr("href"));
});
现在,只要我单击任何链接,Ajax内容就会成功加载,它就会更新我的地址栏.我对这个API有点陌生,所以我不知道我缺少什么,但是到目前为止这是我的问题:
Now it updates my address bar whenever i click on any of my links and the ajax content gets successfully loaded.I am kinda new to this API so i don't know what am i missing but here are my issues so far:
-
当我按下返回"按钮时,什么也没发生.我阅读了有关"popstate"的内容,并浏览了SO以寻找解决方案,但我无法似乎使它们起作用.
when i press the "back" button, nothing happens. I read about "popstate" and browsed through SO to look for solutions but i can'tseem to make them work.
当我单击历史记录中的链接时,我获得了子html的原始"视图,而没有来自主html的布局.如果我想像这样显示它该怎么办是从我的主应用程序中单击的吗?
When i click the link from the history, i get the "raw" view of the child html w/o the layout from the master html. What do i need to do if i want it to be displayed likeit was clicked from my main application?
我的大多数子视图都是表格或列表.
Most of my child views are either forms or list.
推荐答案
此代码应为您提供帮助:
This code should help you :
function openURL(href){
var link = href; //$(this).attr('href');
$.ajax({
url: link,
type: 'POST',
cache: false,
success: function (result) {
$('#target').html(result);
$.validator.unobtrusive.parse($("form#ValidateForm"));
}
});
window.history.pushState({href: href}, '', href);
}
$(document).ready(function() {
$(document).on('click', 'a', function () {
openURL($(this).attr("href"));
return false; //intercept the link
});
window.addEventListener('popstate', function(e){
if(e.state)
openURL(e.state.href);
});
});
这篇关于在jQuery Ajax上使用history.pushstate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!