사용자가 링크를 클릭 할 때 XMLHttpRequests를 사용하여 웹 페이지의 일부를 요청하는 웹 사이트가 있습니다.AJAX 페이지 load/history.pushState가 웹 사이트를 탐색 한 후 제대로 작동하지 않습니다.
관련 코드 :
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>
모든 ... 제외 구성 (페이지 로딩, 사이트 내 뒤로/앞으로 버튼을 탐색 ), 로 작동 외부 링크 (클릭 핸들러가 부착되지 않은 경우 크로스 원점이므로) 브라우저의 뒤로 버튼을 누르면 XHR의 응답 인 인사말을받습니다. 단순히 콘텐츠 인 <html>
, <head>
또는 <body>
태그는 CSS 또는 JavaScript를 의미하지 않습니다.
이 경우 어떻게 브라우저에 전체 페이지를로드 할 수 있습니까?
이상한 현상이 ... 감사합니다! – Hatchet