简体   繁体   English

使用 Ajax 加载页面时,返回按钮不起作用

[英]When load page with Ajax, the go back button doesn't works

I'am trying to create a website where all pages are called with Ajax.我正在尝试创建一个网站,其中所有页面都使用 Ajax 调用。 When I click on any link on the page, the url and page content changes without refreshing all page (similar Facebook).当我点击页面上的任何链接时,url 和页面内容都会发生变化,而不会刷新所有页面(类似于 Facebook)。 So far everything is fine.到目前为止一切都很好。

The problem is : When I click the go back or go forward button, the url changes but the page content does not change.问题是:当我单击返回前进按钮时,url 更改但页面内容没有更改。

Example code :示例代码:

function loadDoc($link) {  // example for $link : /example.php
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                var parser = new DOMParser();
                var doc = parser.parseFromString(xhttp.responseText, "text/html");
                var elem = doc.getElementById("content");
                document.getElementById("content").innerHTML = elem.innerHTML;
            }
        };
        xhttp.open("GET", $link, true);
        xhttp.send();
        window.history.pushState('', 'Settings', $link);  // dynamic url changing 
    }

(Fully separate structure or additional ideas are welcomed too) (也欢迎完全独立的结构或其他想法)

You've used pushState to add an entry to the browser history, but you haven't added an event handler to determine what happens when the browser navigates back.您已使用pushState向浏览器历史记录添加条目,但尚未添加事件处理程序来确定浏览器返回时会发生什么。 The browser won't automatically memorise the state of the DOM for you.浏览器不会自动为您记住 DOM 的状态。

Here is a simple example:这是一个简单的例子:

<div id="content">1</div>
<button>1</button>
<button>2</button>
<button>3</button>
<button>4</button>

<script>
    const div = document.querySelector('div');

    addEventListener('click', event => {
        if (event.target.tagName.toLowerCase() !== 'button') return;
        const last = div.textContent;
        const next = event.target.textContent;
        div.textContent = next;
        history.pushState({ value: next }, `Page ${next}`, `/page/${next}`);
    });

    addEventListener('popstate', event => {
        let state = event.state;
        if (state === null) {
            // special case: This is the state before pushState was called
            // We know what that should be:
            state = { value: 1 };
        }
        div.textContent = state.value;
        console.log('location: ' + document.location + ', state: ' + JSON.stringify(event.state));
    });
</script>

You don't have to return the page every time as content in your queries.您不必每次都将页面作为查询中的内容返回。 With REST APIs, you can process your data using tools such as React on the front, by calling only the necessary data.借助 REST API,您可以在前端使用 React 等工具处理数据,只需调用必要的数据即可。 See how REST APIs works and how React manages pages.了解 REST API 如何工作以及 React 如何管理页面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM