jquery - 使用 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"})
})
}
})
})
解决方案
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"})
})
}
})
推荐阅读
- sql - 如何使用连接性能修复 postgresql 更新?
- sas - 从 SAS 上的一行 CSV 数据创建表
- r - r:如何使用带有 sf 几何列的 data.table 包?
- lua - || 在 roblox 上使用 Humanoid:MoveTo() 时出错
- apache-spark - 是否可以获得正在运行的 Spark 任务的尝试次数?
- laravel - 如何解决此错误,此路由不支持 GET 方法。支持的方法:POST
- python-3.x - ValueError:没有足够的值在 tfds.load 中解压
- google-sheets - 创建查询公式
- python - 使用 Python 进行坐标变换时的蒙特卡洛积分
- r - 在 R 线图中包含 facet_wrap