繁体   English   中英

浏览网站后,AJAX页面load / history.pushState无法正常工作

[英]AJAX page load/history.pushState not working properly after navigating off website

我有一个网站,当用户单击链接时,该网站使用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>

一切都按预期进行(页面加载,网站的后退/前进按钮导航), 除非 ...如果单击外部链接(单击处理程序未附加到该外部链接,因为这是跨源链接),然后按浏览器上的后退按钮,我对XHR的响应表示欢迎-只是内容,没有<html><head><body>标记,这意味着也没有CSS或JavaScript。

发生这种情况时,如何使浏览器加载整个页面?

您是否使用相同的URL检索两种不同类型的内容?

如果是这样,我有完全相同的问题。 我使用相同的URL和不同的请求标头返回html应用程序页面或一些JSON数据。 经过history.pushState调用并导航离开后,单击返回将导致JSON响应显示在浏览器中(因为这是与URL关联的浏览器缓存的最后一个响应)。

看来浏览器仅跟踪URL及其响应。 浏览器不会跟踪使用XHR请求标头来指定您真正想要的内容类型。 因此,当您导航离开并返回时,所有浏览器都具有URL(可能还有缓存的响应)。

我的解决方法是,从用于修改浏览器历史记录的URL中更改实际获取JSON数据的URL。

// on click of product item 123
var url = 'http://<webserver>/products/123',
    title = 'Product 123';

history.pushState({
        url: url,
        title: title
    }, title, url);

product = $.getJSON(url + '?json=1'); // make the url different

我整理了一些小测试以突出显示其工作原理https://github.com/robbishop/history-api-test

我已经在一些浏览器中进行了尝试,并注意到Firefox(版本50.0)与Chrome的工作方式不同。 例如,如果您修改页面内容,然后使用伪造的URL调用history.pushState,然后导航离开,然后单击返回。 在Chrome中,您会找到未找到的404页面(因为URL不是真实的),但是在Firefox中,它实际上是还原了您上次看到的页面。 因此,浏览器也存在一些差异,但是我认为直接操作浏览器历史记录时将URL与单一内容类型相关联可能更安全

暂无
暂无

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

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