带有PopState和AJAX的HTML5历史API不断重新加载页面



我目前正在通过Ajax将数据加载到页面上,并通过pushState更新url,没有错误。popstate将完整的对象返回到控制台中,用于查看目的。

我正处于前进和后退按钮部分工作的阶段,这意味着,有时当url更改时,它会重新显示内容,但大多数时候它只是重新加载页面,这会阻止应用程序的顺利运行。

一直在无休止地工作,试图让事情发挥作用,但没有成功:(

我只是不明白为什么页面一直在重新加载并恢复到第一个实例。

我认为这可能与第一次查看页面时是否设置状态有关。

下面的代码在加载时触发Ajax请求,然后在用户更改下拉列表时更新页面内容。

$(function() {
"use strict";
var $results  = $('#results');
// First dataset when page loads
(function(){
var x = 'https://swapi.co/api/people/';
var swFirstCall = $.ajax({
dataType: 'json',
url: x,
async: false
});
swFirstCall.done(function(data) {
var template = $('#results_tpl').html();
var html = Mustache.render(template, data);
$results.html(html);
});
})();
// New dataset based on selected category
$(document).on('change', '#categories', function(e){
e.preventDefault();
var category = this.value; // get selected value
var x = 'https://swapi.co/api/' + category + '/';
var swChangeCall = $.ajax({
dataType: 'json',
url: x,
async: false
});
swChangeCall.done(function(data) {
var template = $('#results_tpl').html();
var html = Mustache.render(template, data);
$('#results').html(html);
console.log("Category: " + category);
window.history.pushState(
// data
// title
// url
category,
category,
window.location.pathname + '?page=' + category
);
});
});
window.addEventListener('popstate', function(event) {
window.location.href = window.location.href;
console.log(event);
return(event);
});
});

非常感谢您的帮助。我已经搜索了Stackoverflow和许多其他资源,但无法理解。

Codepen(如果它有助于查看代码(。

谢谢Barry

pushState时,您要做的是将datacategory变量存储在历史状态对象中。稍后,当您触发popstate事件时,您将退出该状态(用户来回移动(。使用从popstate事件中获得的值,您将需要重新发送页面。我对pushState函数和popstate处理程序进行了更改,以展示如何做到这一点。最后,您需要遵循其中一条注释中关于在ajax调用中删除async: false选项的建议——没有理由像这样拖延脚本执行的其余部分。

编辑:忘了提一下,你会想在第一页加载时初始化你的状态对象。使用replaceState方法执行此操作,因为您不想创建另一个历史记录条目。相反,您希望修改当前历史记录条目,以包括用户返回初始页面时要返回的categorydata。有关包含replaceState调用的swFirstCall.done方法,请参见下文。

// ...
swFirstCall.done(function(data) {
var template = $('#results_tpl').html();
var html = Mustache.render(template, data);
$results.html(html);
// initialize history state object
window.history.replaceState(
{ category: 'Select Category', data  },
null,
'',
);
// ...
window.history.pushState(
// data
// title
// url
{ category, data },
category,
window.location.pathname + '?page=' + category
);
// ...
window.addEventListener('popstate', function(event) {
window.location.pathname + '?page=' + event.state.category;
var template = $('#results_tpl').html();
var html = Mustache.render(template, event.state.data);
$('#results').html(html);
$('#categories').val(event.state.category);
});
// ..

最新更新