如何使用history.pushState更改url以使用jQuery Ajax创建页面转换?

问题描述 投票:0回答:1

我正在尝试使用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.htmlhttp://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
            }
        });
    });
javascript jquery transition
1个回答
1
投票

如果您尝试更改http://www.example.com/index.html中的URL,则不会收到该错误消息。

null来源是页面上的一个,其URL以file:开头。

您需要在一个源不是null的页面中运行JS。即在具有HTTP(S)URL的Web服务器上。

© www.soinside.com 2019 - 2024. All rights reserved.