javascript - window.history.pushState 刷新浏览器

标签 javascript php html browser pushstate

我正在编写一些 javascript 代码,并使用 window.History.pushState 加载新的 HTML 页面,而不是使用 href 标签.我的代码(工作正常)看起来像这样。

window.History.pushState({urlPath:'/page1'},"",'/page1')

奇怪的是,这失败,即重新加载浏览器

window.History.pushState({urlPath:'/page2.php'},"",'/page2.php')

但这有效,内容已更新,浏览器未刷新! (注意 URL 是绝对的而不是相对的)

window.History.pushState({urlPath:'www.domain.com/page2.php'},"",'www.domain.com/page2.php')

documentation for window.History.pushState 表示第三个参数 URL 可以是绝对的也可以是相对的 -

URL — The new history entry's URL is given by this parameter. Note that the browser won't attempt to load this URL after a call to pushState(), but it might attempt to load the URL later, for instance after the user restarts the browser. The new URL does not need to be absolute; if it's relative, it's resolved relative to the current URL. The new URL must be of the same origin as the current URL; otherwise, pushState() will throw an exception. This parameter is optional; if it isn't specified, it's set to the document's current URL.

绝对 URL 似乎有效,但相对似乎无效。为什么会这样?

最佳答案

简短的回答是history.pushState(不是History.pushState,会抛出异常,window部分是可选的)永远不会按照你的建议去做。

如果页面正在刷新,那么它是由您正在执行的其他操作引起的(例如,在地址栏更改的情况下,您可能正在运行的代码转到新位置)。

history.pushState({urlPath:'/page2.php'},"",'/page2.php') 的工作方式与最新版本的 Chrome、IE 中的工作方式完全相同和 Firefox 供我和我的同事使用。

事实上,您可以在函数中添加任何您喜欢的内容:history.pushState({}, '', 'So long and Thanks for all the fish.not a real file')

如果您发布更多代码(特别注意 history.pushState 附近的代码以及使用 document.location 的任何地方),那么我们将不仅仅是很高兴帮助您找出这个问题的确切来源。

如果您发布更多代码,我会更新这个答案(我收藏了您的问题):)。

关于javascript - window.history.pushState 刷新浏览器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24307401/

相关文章:

php - 在包含的文件中使用关键字范围

html - 在不同级别的元素中选择给定类型的最后一个子元素

javascript - 使用详细信息和摘要标签作为可折叠的内联元素

javascript - 如何将元素的每个单词包装在 span 标签中?

javascript - FullCalendar 仅在周 View 和日 View 中显示事件,但不在月 View 中显示事件

javascript - 将列表项设置为负顶部的动画会使其他列表项下降

html - 适用于 Firefox 和 Chrome;不在 IE8 上

javascript - 对象没有转换成函数。未捕获的类型错误 : Cannot read property 'call' of undefined

php - 使用 PHP 检查 Azure AD 中的用户凭据

php - MYSQL查询只能得到最后的结果?