[英]Why doesn't the button for a slide open menu work when i go to a different page but on the main page it works?
[英]When load page with Ajax, the go back button doesn't works
我正在尝试创建一个网站,其中所有页面都使用 Ajax 调用。 当我点击页面上的任何链接时,url 和页面内容都会发生变化,而不会刷新所有页面(类似于 Facebook)。 到目前为止一切都很好。
问题是:当我单击返回或前进按钮时,url 更改但页面内容没有更改。
示例代码:
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
}
(也欢迎完全独立的结构或其他想法)
您已使用pushState
向浏览器历史记录添加条目,但尚未添加事件处理程序来确定浏览器返回时会发生什么。 浏览器不会自动为您记住 DOM 的状态。
这是一个简单的例子:
<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>
您不必每次都将页面作为查询中的内容返回。 借助 REST API,您可以在前端使用 React 等工具处理数据,只需调用必要的数据即可。 了解 REST API 如何工作以及 React 如何管理页面。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.