【发布时间】:2019-01-12 09:48:39
【问题描述】:
我目前正在通过 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如果有助于查看代码。
谢谢,巴里
【问题讨论】:
-
永远不要在 ajax 中使用
async: false...这是一种可怕的做法,并且已被浏览器供应商弃用。从来没有任何充分的理由需要它。您应该会在浏览器控制台中看到有关弃用的警告 -
我删除了
async: false并且错误消失了:)Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience.我意识到.done和.then可以用来代替它。这背后的原因是因为在某些情况下,我需要来自第一个 ajax 请求的特定项目的id,以便第二个 ajax 请求可以工作。 -
在这种情况下,在第一次完成后提出第二次请求
-
如上面提到的@charlietfl 使用
.done或.then可以实现吗? -
对于像 ajax 这样本质上是异步的东西,你必须学习如何异步处理它们。
then()是一个承诺回调,承诺是异步的。忘记async:false甚至存在
标签: javascript jquery html html5-history