Javascript 在jquery ajax上使用history.pushstate
我有一个基于ajax的应用程序,其中我只有一个登录页面和主页 我的大多数链接都是“ajaxed”,我的链接是这样做的:Javascript 在jquery ajax上使用history.pushstate,javascript,jquery,ajax,Javascript,Jquery,Ajax,我有一个基于ajax的应用程序,其中我只有一个登录页面和主页 我的大多数链接都是“ajaxed”,我的链接是这样做的: //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 li
//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”,到目前为止,我所做的第一步是添加以下代码:
$(document).on('click', 'a', function () {
history.pushState({}, '', $(this).attr("href"));
});
现在,每当我点击任何链接时,它都会更新我的地址栏,并且ajax内容会成功加载。
我对这个API有点陌生,所以我不知道我遗漏了什么,但到目前为止我的问题如下:
我的大多数子视图都是表单或列表 此代码应该可以帮助您:
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);
});
});
在使用应用程序时,您需要在用户遇到的所有URL上提供真实页面。这意味着它们需要可书签和刷新。这将很难做到,除非你有一个不同的地方加载内容,而不是回收面向用户的href来存储html部分。如果您从其他地方获得内容,您可以在所有面向用户的URL上提供完全相同的页面,并使用JS onload填写正确的内容。您能解释一下原因吗?pushState()方法用于创建新的历史记录条目。您可以存储状态、标题、url。存储与新历史记录项关联的数据。状态对象将用于存储与新历史记录项关联的数据。如果活动历史记录项发生更改,将对窗口对象触发popstate事件。最常见的情况是在单击浏览器后退或前进按钮或执行后退()、前进()或前进()方法时。是否可以在每次触发
popstate
时调用pushState
?这一行可能应该在$(文档)中。在('click','a'
块上?