【问题标题】:Changing page URL with pushstate preventing ajax from working使用 pushstate 更改页面 URL 以防止 ajax 工作
【发布时间】:2019-06-10 13:35:10
【问题描述】:

我正在尝试伪造页面 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"})

    })
  }
})

})

【问题讨论】:

    标签: jquery ajax browser-history pushstate


    【解决方案1】:

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

    【讨论】:

    • Doh,多年来一直试图解决这个问题,但您只用了几分钟就解决了!哈哈,谢谢洛文!
    猜你喜欢
    • 1970-01-01
    • 2015-12-11
    • 1970-01-01
    • 2019-12-26
    • 1970-01-01
    • 2011-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多