【发布时间】:2020-12-29 12:56:32
【问题描述】:
在两个不同的页面上,我试图在不重新加载页面的情况下更改 URL。我还需要前进和后退浏览器按钮才能转到原始 URL,而不是新 URL。
我创建了一个开关来确定我是否在需要更改 URL 的页面之一上。
然后我根据this answer 组合了一个用于更改 URL 的 sn-p。但这就是我卡住的地方。
因为我不确定我应该如何调用processAjaxData,我认为这是我传入新 URL slug 的地方。另外我应该为response 传递什么?
<script>
var windowLoc = jQuery(location).attr('pathname'); //jquery format to get window.location.pathname
switch (windowLoc) {
case "/the-old-url-I-want-to-change/":
function processAjaxData(response, urlPath) {
document.getElementByClass("page").innerHTML = response.html;
document.title = response.pageTitle;
window.history.pushState({"html": response.html, "pageTitle": response.pageTitle}, "", urlPath);
}
window.onpopstate = function(e) {
if (e.state) {
document.getElementByClass("page").innerHTML = e.state.html;
document.title = e.state.pageTitle;
}
};
break;
case "/another-old-url-I-want-to-change/":
function processAjaxData(response, urlPath) {
document.getElementByClass("page").innerHTML = response.html;
document.title = response.pageTitle;
window.history.pushState({"html": response.html, "pageTitle": response.pageTitle}, "", urlPath);
}
window.onpopstate = function(e) {
if (e.state) {
document.getElementByClass("page").innerHTML = e.state.html;
document.title = e.state.pageTitle;
}
};
break;
}
</script>
【问题讨论】:
标签: javascript ajax url