如何将 url 更改为 history.pushState 以创建具有 jQuery Ajax 的页面转换?

How to change the url with history.pushState to create a page transition with jQuery Ajax?

我正在尝试使用 window.history.pushState() 实现无缝页面转换,以更改地址栏中的 url。我遵循了这个 tutorial,但是 pushState 抛出了以下错误:Uncaught DOMException: Failed to execute 'pushState' on 'History': A history state object with URL [link] cannot be created in a document with origin 'null' and URL

有谁知道如何解决这个问题。我想要实现的是,获取被单击的按钮的 href 并将 url 例如从:http://www.example.com/index.html 更改为 http://www.example.com/about.html

$('.button').on('click', function(e) {
        e.preventDefault();

        var href = $(this).attr('href');
        window.history.pushState(null, null, href); 

        $.ajax({
            url: href,
            success: function(data) {
                // Do animation and change content
            }
        });
    });

如果您尝试将 URL 从 http://www.example.com/index.html 更改为

,则不会收到该错误消息

null 来源是页面上的一个 URL 开始 file:

您需要 运行 来源不是 null 的页面中的 JS。即在具有 HTTP(S) URL.

的 Web 服务器上