jquery:如何在新选项卡中打开一个URL,并将帖子数据传递到该URL


jquery: how to open an url in new tab with passing post data to that url

我有一个php文件localhost/~user/sample.php文件,它从post方法获取数据。

<?php
$you = $_POST["ids"];
$start= $_POST["start"];
echo $you."--".$start;

我想编写一个 jquery 代码,它将在我的 html 页面内的按钮单击时在单独的窗口中打开 url"localhost/~user/sample.php",并传递它所需的参数。

我可以在 php 中使用 get 方法,但变量的数量更多

我可能会使用表单,如下所示:

<form action="sample.php" method="post" target="_blank">
  <input type="hidden" name="name1" />
  <input type="hidden" name="name2" />
  ...
  <input type="hidden" name="name20" />
  <input type="submit" value="Go to page">
</form>

这是我能想到的实现此任务的最跨浏览器的 JS-failsafe 基本 html 版本方法......

如果您需要动态地将表单字段添加到表单中,我相信您会发现这个问题:Jquery - 即时创建隐藏的表单元素很方便。复制修改后的答案:

$('<input type="hidden" name="myfieldname" value="myvalue">').appendTo('form');

一种方法是动态创建一个隐藏表单,然后提交它,确保对输入进行编码

var params = [['someKey0', 'someValue0'], ['someKey1', 'someValue1'], ['someKey2', 'someValue2'], ['someKey3', 'someValue3']];
var inputs = $.map(params,function(e,i){
  return '<input type="hidden" name="'+e[0]+'" value="'+encodeURIComponent(e[1])+'"/>';
});
var form ='<form action="sample.php" id="hidden-form" method="post" target="_blank">'+inputs.join('')+'</form>';
$('#hidden-div').html(form);
$('#hidden-form').submit();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="hidden-div"></div>

试试这个....

<form id="myForm" action="sample.php" method="post">
<?php
     echo '<input type="hidden" name="'.htmlentities($you).'" value="'.htmlentities($start).'">';
?>
</form>
<script type="text/javascript">
    document.getElementById('myForm').submit();
</script>

如果你使用 JavaScript 向任何 PHP 页面发送请求;它会发送一个请求并获取已发送请求的页面的响应,然后你继续在第一页处理你的数据。因此,如果您想打开样品.php并在其中发送您的帖子数据;您必须使用 PHP 表单之类的东西发送数据。

提交表格:http://www.w3schools.com/php/php_forms.asp

如果你想使用 js post,你可以做如下的事情:

团队.php:

data = { teams : ['Real Madrid','Barcelona','etc']};
var response = null;
$.ajax({
    url : 'mypostfile.php',
    type : 'POST',
    data : data
})
.done(function(resp){ response = resp; //it returned from php echo  })
.fail(function(){   console.log('fail'); //post process failed. });

我的邮.php文件:

if(isset($_POST['teams'])){
   $teams = $_POST['teams'];
   echo $teams[0]; //response : Real Madrid
}

希望对您有所帮助。