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

}

当前回答

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

其他回答

没有解决方案。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。位置。

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

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

还有别的办法吗?

使用起来非常方便:

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