使用 JavaScript/jQuery 在重定向时发送 POST 数据?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8389646/
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-24 05:48:07  来源:igfitidea点击:

Send POST data on redirect with JavaScript/jQuery?

javascriptjquerypost

提问by Josh Foskett

Basically what I want to do is send POSTdata when I change the window.location, as if a user has submitted a form and it went to a new page. I need to do it this way because I need to pass along a hidden URL, and I can't simply place it in the URL as a GETfor cosmetic reasons.

基本上我想要做的是POST在我更改 时发送数据window.location,就好像用户提交了一个表单并转到了一个新页面。我需要这样做,因为我需要传递一个隐藏的 URL,并且GET出于美观的原因,我不能简单地将它放在 URL 中。

This is what I have at the moment, but it doesn't send any POST data.

这是我目前所拥有的,但它不发送任何 POST 数据。

if(user has not voted) {

    window.location = 'http://example.com/vote/' + Username;

}

I know that you can send POSTdata with jQuery.post(), but I need it to be sent with the new window.location.

我知道您可以使用 发送POST数据jQuery.post(),但我需要使用新的window.location.

So to recap, I need to send api_urlvalue via POSTto http://example.com/vote/, while sending the user to the same page at the same time.

因此,要回顾一下,我需要发送api_url通过价值POSThttp://example.com/vote/,而在同一时间向用户发送到同一页面。



For future reference, I ended up doing the following:

为了将来参考,我最终做了以下事情

if(user has not voted) {

    $('#inset_form').html('<form action="http://example.com/vote/' + Username + '" name="vote" method="post" style="display:none;"><input type="text" name="api_url" value="' + Return_URL + '" /></form>');

    document.forms['vote'].submit();

}

采纳答案by Kevin Reid

Construct and fill out a hidden method=POST action="http://example.com/vote"form and submit it, rather than using window.locationat all.

构建并填写一个隐藏的method=POST action="http://example.com/vote"表单并提交它,而不是使用它window.location

回答by tardate

per @Kevin-Reid's answer, here's an alternative to the "I ended up doing the following" example that avoids needing to name and then lookup the form object again by constructing the form specifically (using jQuery)..

根据@Kevin-Reid 的回答,这里有一个替代“我最终做了以下事情”的例子,它避免了命名,然后通过专门构造表单(使用 jQuery)来再次查找表单对象。

var url = 'http://example.com/vote/' + Username;
var form = $('<form action="' + url + '" method="post">' +
  '<input type="text" name="api_url" value="' + Return_URL + '" />' +
  '</form>');
$('body').append(form);
form.submit();

回答by tfont

Here's a simple small function that can be applied anywhere as long as you're using jQuery.

这是一个简单的小函数,只要您使用 jQuery,它就可以应用于任何地方。

var redirect = 'http://www.website.com/page?id=23231';
$.redirectPost(redirect, {x: 'example', y: 'abc'});

// jquery extend function
$.extend(
{
    redirectPost: function(location, args)
    {
        var form = '';
        $.each( args, function( key, value ) {
            value = value.split('"').join('\"')
            form += '<input type="hidden" name="'+key+'" value="'+value+'">';
        });
        $('<form action="' + location + '" method="POST">' + form + '</form>').appendTo($(document.body)).submit();
    }
});

回答by Tom Sarduy

If you are using jQuery, there is a redirect pluginthat works with the POST or GET method. It creates a form with hidden inputs and submits it for you. An example of how to get it working:

如果您使用的是 jQuery,则有一个可与 POST 或 GET 方法配合使用的重定向插件。它创建一个带有隐藏输入的表单并为您提交。如何让它工作的一个例子:

$.redirect('demo.php', {'arg1': 'value1', 'arg2': 'value2'});

Note:You can pass the method types GET or POST as an optional third parameter; POST is the default.

注意:您可以将方法类型 GET 或 POST 作为可选的第三个参数传递;POST 是默认设置。

回答by olee

Here is a method, which does not use jQuery. I used it to create a bookmarklet, which checks the current page on w3-html-validator.

这是一个方法,它不使用 jQuery。我用它来创建一个书签,它检查 w3-html-validator 上的当前页面。

var f = document.createElement('form');
f.action='http://validator.w3.org/check';
f.method='POST';
f.target='_blank';

var i=document.createElement('input');
i.type='hidden';
i.name='fragment';
i.value='<!DOCTYPE html>'+document.documentElement.outerHTML;
f.appendChild(i);

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

回答by webs

The answers here can be confusing so i will give you a sample code that i am working with.

这里的答案可能会令人困惑,所以我会给你一个我正在使用的示例代码。

To start with note that there is no POST parameter to java script windows.location function that you are referring to.

首先请注意,您所指的 java 脚本 windows.location 函数没有 POST 参数。

So you have to...

所以你必须...

  1. Dynamically make a form with a POST parameter.

  2. Dynamically put a textbox or textboxes with your desired values to post

  3. Invoke the submit form you dynamically created.

  1. 动态创建带有 POST 参数的表单。

  2. 动态地放置一个或多个具有您想要的值的文本框来发布

  3. 调用您动态创建的提交表单。

And for the example.

例如。

     //---------- make sure to link to your jQuery library ----//

<script type="text/javascript" >

    var form = $(document.createElement('form'));
    $(form).attr("action", "test2.php");
    $(form).attr("method", "POST");
    $(form).css("display", "none");

    var input_employee_name = $("<input>")
    .attr("type", "text")
    .attr("name", "employee_name")
    .val("Peter" );
    $(form).append($(input_employee_name));


    var input_salary = $("<input>")
    .attr("type", "text")
    .attr("name", "salary")
    .val("1000" );
    $(form).append($(input_salary));

    form.appendTo( document.body );
    $(form).submit();

</script>

If all is done well, you shall be redirected to test2.php and you can use POST to read passed values of employee_name and salary; that will be Peter and 1000 respectively.

如果一切顺利,您将被重定向到 test2.php ,您可以使用 POST 读取员工姓名和工资的传递值;那将分别是 Peter 和 1000。

On test2.php you can get your values thus.

在 test2.php 上,您可以获得您的值。

$employee_name = $_POST['employee_name'];
$salary = $_POST['salary'];

Needless to say , make sure you sanitize your passed values.

不用说,请确保对传递的值进行消毒。

回答by therealrootuser

Generic function to post any JavaScript object to the given URL.

将任何 JavaScript 对象发布到给定 URL 的通用函数。

function postAndRedirect(url, postData)
{
    var postFormStr = "<form method='POST' action='" + url + "'>\n";

    for (var key in postData)
    {
        if (postData.hasOwnProperty(key))
        {
            postFormStr += "<input type='hidden' name='" + key + "' value='" + postData[key] + "'></input>";
        }
    }

    postFormStr += "</form>";

    var formElement = $(postFormStr);

    $('body').append(formElement);
    $(formElement).submit();
}

回答by Ali John

This is quite handy to use:

这使用起来非常方便:

var myRedirect = function(redirectUrl, arg, value) {
  var form = $('<form action="' + redirectUrl + '" method="post">' +
  '<input type="hidden" name="'+ arg +'" value="' + value + '"></input>' + '</form>');
  $('body').append(form);
  $(form).submit();
};

then use it like:

然后像这样使用它:

myRedirect("/yourRedirectingUrl", "arg", "argValue");

回答by Rajesh

var myRedirect = function(redirectUrl) {
var form = $('<form action="' + redirectUrl + '" method="post">' +
'<input type="hidden" name="parameter1" value="sample" />' +
'<input type="hidden" name="parameter2" value="Sample data 2" />' +
'</form>');
$('body').append(form);
$(form).submit();
};

Found code at http://www.prowebguru.com/2013/10/send-post-data-while-redirecting-with-jquery/

http://www.prowebguru.com/2013/10/send-post-data-while-redirecting-with-jquery/找到代码

Going to try this and other suggestions for my work.

打算为我的工作尝试这个和其他建议。

Is there any other way to do the same ?

有没有其他方法可以做到这一点?

回答by joni jones

You can use targetattribute to send form with redirect from iframe. Your form open tag would be something like this:

您可以使用target属性从 iframe 发送带有重定向的表单。您的表单打开标签将是这样的:

method="post" action="http://some.url.com/form_action" target="_top"