【发布时间】:2016-10-18 19:39:50
【问题描述】:
我有一个网站,当用户单击链接时,它使用 XMLHttpRequests 请求部分网页。
相关代码:
function requestPage(url, push) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
main.innerHTML = xhr.responseText;
attachLinkClickHandlers(main); // `main` = container element
if (push)
window.history.pushState(url, title, url);
}
};
xhr.open('GET', url);
xhr.setRequestHeader('Content-Only', 1); // Server responds to Content-Only header by not sending everything surrounding the main content.
xhr.send();
}
window.addEventListener('popstate', function (e) {
var page = e.state;
requestPage(page, false);
});
window.history.replaceState(location.href, document.title, location.href);
attachLinkClickHandlers(document);
点击链接:
requestPage(link.href, true);
示例服务器响应:
正常请求响应:
<!doctype html>
<html>
<head>
...stuff...
</head>
<body>
...stuff...
<main>
<h1>Content</h1>
<p>Content Content</p>
</main>
...stuff...
</body>
</html>
带有Content-Only 标头集的响应:
<h1>Content</h1>
<p>Content Content</p>
一切都按预期工作(页面加载、后退/前进按钮导航网站内),除了...如果我点击一个外部 em> 链接(点击处理程序未附加到该链接,因为那将是跨源的),然后按浏览器上的后退按钮,我很高兴 XHR 的响应是什么 - 只是内容,没有 @ 987654326@、<head> 或 <body> 标签,这意味着也没有 CSS 或 JavaScript。
发生这种情况时如何让浏览器加载完整页面?
【问题讨论】:
标签: javascript ajax http-headers xmlhttprequest html5-history