Javascript POST 后重新加载浏览器窗口而不提示用户重新发送 POST 数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4869721/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:31:35  来源:igfitidea点击:

Reload browser window after POST without prompting user to resend POST data

javascript

提问by Scott Mitchell

When a user visits my website there is a "Login" link on every page. Clicking this uses some JavaScript to show an overlay window where the user is prompted for their credentials. After entering these credentials an Ajax call is made to the web server to validate them; if they are valid, an authentication ticket cookie is sent back and the page is reloaded so that any content on the page that is specific to authenticated users or the (now) currently logged in user is displayed.

当用户访问我的网站时,每个页面上都有一个“登录”链接。单击它会使用一些 JavaScript 来显示一个覆盖窗口,提示用户输入他们的凭据。输入这些凭据后,会对 Web 服务器进行 Ajax 调用以验证它们;如果它们有效,则发送回身份验证票证 cookie 并重新加载页面,以便显示页面上特定于经过身份验证的用户或(现在)当前登录用户的任何内容。

I am accomplishing the page reload via script using:

我正在使用以下脚本通过脚本完成页面重新加载:

window.location.reload();

This works wonderfully for pages loaded via a GET request (the vast majority), but some pages use postback forms. So if a user goes to one of these pages, performs a postback, and then chooses to login, when the window.location.reload()script runs they are prompted with the dialog box asking if they want to resubmit the POST body.

这对于通过 GET 请求(绝大多数)加载的页面非常有效,但有些页面使用回发表单。因此,如果用户转到这些页面之一,执行回发,然后选择登录,则当window.location.reload()脚本运行时,会出现对话框提示他们是否要重新提交 POST 正文。

Resubmit POST body dialog box

重新提交 POST 正文对话框

I thought to get around this I could just tell the browser to reload the page, so I tried:

我想解决这个问题,我可以告诉浏览器重新加载页面,所以我尝试了:

window.location.href = window.location.href;

But the browser doesn't take any action with the above statement, I presume because it's thinking the new URL is the same as the old. If I change the above to:

但是浏览器不会对上述语句采取任何操作,我推测是因为它认为新 URL 与旧 URL 相同。如果我将上述更改为:

window.location.href = window.location.pathname;

It reloads the page, but I lose any querystring parameters.

它重新加载页面,但我丢失了任何查询字符串参数。

My current workaround is sufficient, but not pretty - in short, I tack on a querystring parameter to the current window.location.hrefvalue and then assign that back to window.location.hrefby calling reloadPage("justLoggedIn"), where the reloadPagefunction is:

我目前的解决方法是足够的,但不是很好 - 简而言之,我将查询字符串参数附加到当前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;
}

This works, but it results in the URL being www.example.com/SomeFolder/SomePage.aspx?justLoggedIn, which seems tacky.

这有效,但它导致 URL 为www.example.com/SomeFolder/SomePage.aspx?justLoggedIn,这看起来很俗气。

Is there a way in JavaScript to get it to do a GET reload and not prompt the user to resubmit the POST data? I need to make sure that any existing querystring parameters are not lost.

JavaScript 中有没有办法让它执行 GET 重新加载而不提示用户重新提交 POST 数据?我需要确保任何现有的查询字符串参数都不会丢失。

回答by peaceslp

window.location.href = window.location.href;

Don't ask my why it works..but it does :). Just the way the js engine interprets the logic I suppose.

不要问我为什么它有效..但它确实:)。就像 js 引擎解释我想的逻辑一样。

回答by Daniel Doezema

What you probably need to do is redirect the user after the POST / Form Handler script has been ran.

您可能需要做的是在 POST / Form Handler 脚本运行后重定向用户。

In PHP this is done like so...

在 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();
?>

... this shouldallow you to refresh the page without getting that "Send Data Again" warning.

...这应该允许您刷新页面而不会收到“再次发送数据”警告。

You can even redirect to the same page (if that's what you're posting to) as the POST variables will not be sent in the headers (and thus not be there to re-POST on refresh)

您甚至可以重定向到同一页面(如果这是您要发布的页面),因为 POST 变量不会在标头中发送(因此不会在刷新时重新发布)

回答by KF Web Development

This works too:

这也有效:

window.location.href = window.location.pathname + window.location.search

回答by A Web-Developer

This worked for me.

这对我有用。

window.location = window.location.pathname;

window.location = window.location.pathname;

Tested on

经过测试

  • Chrome 44.0.2403
  • IE edge
  • Firefox 39.0
  • 铬 44.0.2403
  • IE边缘
  • 火狐 39.0

回答by Rajendra Prasad Das

Use

RefreshForm.submit(); 

instead of

代替

document.location.reload(true); 

回答by trante

This can be solved also with POST/REDIRECT/GET pattern.
Which is more elegant:
How do I reload a page without a POSTDATA warning in Javascript?

这也可以通过 POST/REDIRECT/GET 模式解决。
哪个更优雅:
如何在 Javascript 中没有 POSTDATA 警告的情况下重新加载页面?

回答by Tiberiu-Ionu? Stan

I had the same problem as you.

我和你有同样的问题。

Here's what I did (dynamically generated GET form with action set to location.href, hidden input with fresh value), and it seems to work in all browsers:

这是我所做的(动态生成的 GET 表单,动作设置为 location.href,隐藏输入具有新值),它似乎适用于所有浏览器:

var elForm=document.createElement("form");
elForm.setAttribute("method", "get");
elForm.setAttribute("action", window.location.href);

var elInputHidden=document.createElement("input");
elInputHidden.setAttribute("type", "hidden");
elInputHidden.setAttribute("name", "r");
elInputHidden.setAttribute("value", new Date().getTime());
elForm.appendChild(elInputHidden);

if(window.location.href.indexOf("?")>=0)
{
    var _arrNameValue;
    var strRequestVars=window.location.href.substr(window.location.href.indexOf("?")+1);
    var _arrRequestVariablePairs=strRequestVars.split("&");
    for(var i=0; i<_arrRequestVariablePairs.length; i++)
    {
        _arrNameValue=_arrRequestVariablePairs[i].split("=");

        elInputHidden=document.createElement("input");
        elInputHidden.setAttribute("type", "hidden");
        elInputHidden.setAttribute("name", decodeURIComponent(_arrNameValue.shift()));
        elInputHidden.setAttribute("value", decodeURIComponent(_arrNameValue.join("=")));
        elForm.appendChild(elInputHidden);
    }
}

document.body.appendChild(elForm);
elForm.submit();

回答by Stephen

This is an older post, but I do have a better solution. Create a form containing all of your post values as hidden fields and give the form a name such as:

这是一个较旧的帖子,但我确实有更好的解决方案。创建一个包含所有帖子值作为隐藏字段的表单,并为表单命名,例如:

<form name="RefreshForm" method="post" action="http://yoursite/yourscript">
    <input type="hidden" name="postVariable" value="PostData">
</form>

Then all you need to do in your setTimeoutis RefreshForm.submit();

那么你需要做的setTimeout就是RefreshForm.submit();

Cheers!

干杯!

回答by Juan Mendes

You could try to create an empty form, method=get, and submitting it.

您可以尝试创建一个空表单,method=get,然后提交。

<form id='reloader' method='get' action="enter url here"> </form>
<script>
// to reload the page, try
document.getElementById('reloader').submit();
</script>

回答by PodTech.io

If you have hashes '#' in your URL, all the solutions here do not work. This is the only solution that worked for me.

如果您的 URL 中有散列“#”,则此处的所有解决方案都不起作用。这是唯一对我有用的解决方案。

var hrefa = window.location.href.split("#")[1];
var hrefb = window.location.href.split("#")[2];
window.location.href  = window.location.pathname +  window.location.search + '&x=x#' + hrefa + '#' + hrefb;

The URL has to be different for it to reload if you have a hash. The &x=x does that here. Just substitute this for something you can ignore. THis is abit of a hack, unable to find a better solution..

如果您有散列,URL 必须不同才能重新加载。&x=x 在这里完成。只需将其替换为您可以忽略的东西。这是一个黑客,无法找到更好的解决方案..

Tested in Firefox.

在 Firefox 中测试。