首页 > 解决方案 > 使用 pushstate 更改页面 URL 以防止 ajax 工作

问题描述

我正在尝试伪造页面 url,同时使用 ajax 来更改页面内容。我还在结合使用 jquery 转换和这个 ajax,但是当我添加 pushstate 来更改 URL 时,它会阻止 ajax 更改页面内容。

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

$("#contactRoll").on("点击", function(event) {

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"})

    })
  }
})

})

标签: jqueryajaxbrowser-historypushstate

解决方案


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

使用 history.pushState() 会更改在更改状态后创建的 XMLHttpRequest 对象的 HTTP 标头中使用的引荐来源网址。在创建 XMLHttpRequest 对象时,引用者将是其窗口是 this 的文档的 URL。

尝试添加

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

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

$.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"})

      })
    }
  })

推荐阅读