基本上我想做的是当我改变窗口时发送POST数据。位置,就好像用户提交了一个表单,然后它转到了一个新页面。我需要这样做,因为我需要传递一个隐藏的URL,我不能简单地将它作为一个GET放在URL中。

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

if(user has not voted) {

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

}

我知道你可以用jQuery.post()发送POST数据,但我需要它与新的window.location一起发送。

因此,概括一下,我需要通过POST将api_url值发送到http://example.com/vote/,同时将用户发送到同一页面。


为了便于将来参考,我最后做了以下工作:

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

}

当前回答

将任何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();
}

其他回答

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

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

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

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

使用起来非常方便:

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();
};

然后这样使用它:

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

每@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();

你可以使用目标属性从iframe重定向发送表单。 你的表单打开标签应该是这样的:

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