首页 > 解决方案 > JavaScript push 和 replaceState 导致前进按钮中断

问题描述

我基本上完成了我的网络应用程序,除了当我尝试使用历史 API 时它会禁用我的前进按钮功能。后退按钮效果很好。据我所知,我没有在 onpopstate 事件侦听器中使用 pushState。请任何人都可以帮助我理解为什么状态消失并且您无法单击前进?我附上相关代码。

if (document.querySelector('#weather-form')) {
    history.pushState({ city: 'none_yet' }, ``, ``);
}


window.onpopstate = function(event) {
var state = event.state;
if (state !== null) {
    console.log(`State 2: ${state['city']}, Window.location: ${window.location}`);
    window.location.reload();
} else {
    console.log(`State 3: ${state}, Window.location: ${window.location}`);
    window.location.reload();
}

}

然后在每当用户提交包含其位置的表单时调用的函数中:

function get_data(city, time, units) {
let cityObj = {
    city: city,
    time: time,
    units: units
};
fetch('http://127.0.0.1:8000/get_data', {
        method: 'POST',
        body: JSON.stringify(cityObj)
    })
    .then(response => response.json())
    .then(response => {
        console.log(response);
        if (response["Error"]) {
            let error_message = document.createElement('h5');
            error_message.id = "error";
            error_message.innerHTML = `The location input '${city}' is invalid. Please try again.`;
            document.querySelector('#main').append(error_message);
        } else {
            history.replaceState({ city: city }, ``, `/city/${city}/`);

非常感谢任何帮助/解释。谢谢。

标签: javascriptweb-frontendpushstatehtml5-historyhistory.js

解决方案


推荐阅读