使用 pushstate 更改页面 URL 阻止 ajax 工作

Changing page URL with pushstate preventing ajax from working

我试图伪造页面 url,同时使用 ajax 来更改页面内容。我也将 jquery 转换与此 ajax 结合使用,但是当我添加 pushstate 以更改 URL 时,它会阻止 ajax 更改页面内容。

如果我注释掉 // window.history.pushState(null, "null", href) 行,那么转换工作正常,但 url 则不会更改。谁能看到我做错了什么?

$("#contactRoll").on("click", 函数(事件) {

event.preventDefault();

$(document).attr("title", "Contact Page");

//get the 'fake' link
const href = $(this).attr("href")

//fake the url
window.history.pushState(null, "null", href)

$('.main-logo').fadeOut(500)
$('.main-logo-reverse').delay(500).fadeIn(300)

$.ajax({
  //set the fake url
  url: href,
  success: function (data) {

    $("header").animate({marginTop: "100vh"}, function () {
      const newPage = $(data).filter("#main").html()

      $("#main").html(newPage)
      $("section#contact").animate({marginTop: "0vh"})

    })
  }
})

})

https://developer.mozilla.org/en-US/docs/Web/API/History_API

Using history.pushState() changes the referrer that gets used in the HTTP header for XMLHttpRequest objects created after you change the state. The referrer will be the URL of the document whose window is this at the time of creation of the XMLHttpRequest object.

尝试添加

//fake the url
window.history.pushState(null, "null", href)

success: function(data) { ... } 回调,以便 url 状态在 Ajax 请求完成后更改。

$.ajax({
    url: href,
    success: function (data) {

        //fake the url
        window.history.pushState(null, "null", href)
        $("header").animate({marginTop: "100vh"}, function () {
        const newPage = $(data).filter("#main").html()

        $("#main").html(newPage)
        $("section#contact").animate({marginTop: "0vh"})

      })
    }
  })