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

}

当前回答

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

其他回答

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/找到代码

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

还有别的办法吗?

没有解决方案。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);

细节

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

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

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

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

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

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