基本上我想做的是当我改变窗口时发送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();
}

其他回答

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

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

我打算试试这个,还有其他一些对我工作的建议。

还有别的办法吗?

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

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

没有解决方案。1

 //your variable
    var data = "brightcherry";

    //passing the variable into the window.location URL
    window.location.replace("/newpage/page.php?id='"+product_id+"'");

没有解决方案。2

//your variable
var data = "brightcherry";

//passing the variable into the window.location URL
window.location.replace("/newpage/page.php?id=" + product_id);

细节

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

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