使用推送状态更改页面 URL,阻止 ajax 工作



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

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

$("#contactRoll").on("click", 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"})

})
}
})
})

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

使用 history.pushState() 更改在更改状态后创建的 XMLHttpRequest 对象的 HTTP 标头中使用的引用器。引荐来源网址将是创建 XMLHttpRequest 对象时其窗口为该窗口的文档的 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"})
})
}
})

最新更新