当用户访问我的网站时,每个页面上都有一个"登录"链接.单击此按钮可使用一些JavaScript显示覆盖窗口,提示用户提供其凭据.输入这些凭证后,将对Web服务器进行Ajax调用以验证它们; 如果它们有效,则会发回验证票证cookie并重新加载页面,以便显示特定于已验证用户或(现在)当前登录用户的页面上的任何内容.
我正在使用以下脚本完成页面重新加载:
window.location.reload();
Run Code Online (Sandbox Code Playgroud)
这非常适用于通过GET请求(绝大多数)加载的页面,但有些页面使用回发表单.因此,如果用户转到其中一个页面,执行回发,然后选择登录,则在window.location.reload()
脚本运行时会通过对话框提示是否要重新提交POST正文.
我想绕过这个我可以告诉浏览器重新加载页面,所以我试过:
window.location.href = window.location.href;
Run Code Online (Sandbox Code Playgroud)
但浏览器不会对上述语句采取任何操作,我认为是因为它认为新URL与旧URL相同.如果我将以上内容更改为:
window.location.href = window.location.pathname;
Run Code Online (Sandbox Code Playgroud)
它重新加载页面,但我丢失了任何查询字符串参数.
我当前的解决方法已经足够了,但并不漂亮 - 简而言之,我将查询字符串参数添加到当前window.location.href
值,然后window.location.href
通过调用将其分配回来reloadPage("justLoggedIn")
,其中reloadPage
函数是:
function reloadPage(querystringTackon) {
var currentUrl = window.location.href;
if (querystringTackon != null && querystringTackon.length > 0 && currentUrl.indexOf(querystringTackon) < 0) {
if (currentUrl.indexOf("?") < 0)
currentUrl += "?" + querystringTackon;
else
currentUrl += "&" + querystringTackon;
}
window.location.href = currentUrl;
}
Run Code Online (Sandbox Code Playgroud)
这可行,但它会导致URL www.example.com/SomeFolder/SomePage.aspx?justLoggedIn
,这似乎很俗气.
在JavaScript中是否有办法让它进行GET重新加载而不提示用户重新提交POST数据?我需要确保任何现有的查询字符串参数都不会丢失.
小智 41
window.location.href = window.location.href;
Run Code Online (Sandbox Code Playgroud)
不要问我为什么它有效..但它确实:).就像js引擎解释我想的逻辑一样.
您可能需要做的是在运行POST/Form Handler脚本后重定向用户.
在PHP中,这样做就像......
<?php
// ... Handle $_POST data, maybe insert it into a database.
// Ok, $_POST data has been handled, redirect the user
header('Location:success.php');
die();
?>
Run Code Online (Sandbox Code Playgroud)
...这应该允许您刷新页面而不会获得"再次发送数据"警告.
您甚至可以重定向到同一页面(如果这是您要发布的内容),因为POST变量不会在标题中发送(因此不会在刷新时重新发布)
小智 7
这也有效:
window.location.href = window.location.pathname + window.location.search
Run Code Online (Sandbox Code Playgroud)
小智 5
使用
RefreshForm.submit();
Run Code Online (Sandbox Code Playgroud)
代替
document.location.reload(true);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
107738 次 |
最近记录: |