Window.open和通过post方法传递参数


97

我使用window.open方法打开了带有参数的新站点,我必须通过post方法来传递它。我找到了解决方案,但不幸的是它不起作用。这是我的代码:

<script  type="text/javascript">    
function openWindowWithPost(url,name,keys,values)
{
    var newWindow = window.open(url, name);

    if (!newWindow) return false;

    var html = "";
    html += "<html><head></head><body><form id='formid' method='post' action='" + url +"'>";

    if (keys && values && (keys.length == values.length))
        for (var i=0; i < keys.length; i++)
            html += "<input type='hidden' name='" + keys[i] + "' value='" + values[i] + "'/>";

    html += "</form><script type='text/javascript'>document.getElementById(\"formid\").submit()</sc"+"ript></body></html>";

    newWindow.document.write(html);
    return newWindow;
}
</script>  

接下来,我创建数组:

<script type="text/javascript">    
var values= new Array("value1", "value2", "value3") 
var keys= new Array("a","b","c") 
</script>  

并通过以下方式调用函数:

<input id="Button1" type="button" value="Pass values" onclick="openWindowWithPost('test.asp','',keys,values)" />   

但是,当我单击此按钮时,站点test.asp为空(当然,我尝试获取传递值- Request.Form("b"))。

我怎么解决这个问题,为什么我不能获得通过值?


2
什么不起作用?我将副本保存在jsfiddle.net/TZMMF上,并且可以正常运行。
2010年

谢谢您的回复。是的,抱歉-上面的代码有效。但是我用键数组测试了此功能:<script type =“ text / javascript”> var values = new Array(“ value1”,“ value2”,“ value3”)var keys = new Array(“ 1”,“ 2 “,” 3“)//代替a,b,c </ script>我通过Request.Form(” 2“)获得了价值在IE和Firefox中,我得到了一个空页面。
luk4443

Answers:


121

无需将表单写入新窗口(要用HTML代码中的值进行编码就很难正确进行),只需打开一个空窗口并将表单发布到该窗口即可。

例:

<form id="TheForm" method="post" action="test.asp" target="TheWindow">
<input type="hidden" name="something" value="something" />
<input type="hidden" name="more" value="something" />
<input type="hidden" name="other" value="something" />
</form>

<script type="text/javascript">
window.open('', 'TheWindow');
document.getElementById('TheForm').submit();
</script>

编辑:

要动态设置表单中的值,您可以执行以下操作:

function openWindowWithPost(something, additional, misc) {
  var f = document.getElementById('TheForm');
  f.something.value = something;
  f.more.value = additional;
  f.other.value = misc;
  window.open('', 'TheWindow');
  f.submit();
}

要发布表单,请使用值调用函数,例如openWindowWithPost('a','b','c');

注意:我改变了与表单名称相关的参数名称,以表明它们不必相同。通常,您将使它们彼此相似,以使其更易于跟踪值。


那正是我的想法。最初发布的代码似乎确实可以正常工作,但IE除外。
站在

谢谢您的回复。但是我有一个表,在列中有按钮。单击此按钮时,我将打开新页面并传递一些参数。因此,我必须编写函数,并为每个按钮调用它并传递固定的参数。我的问题是,我该如何重写您的上述代码以起作用?
luk4443

1
@ luk4443:如果在打开窗口时使用URL,则在您发布表单时将替换页面。将URL放在action表单的属性中。
古法

1
@Guffa还能模拟行为target="_blank"吗?
埃弗顿2014年

2
@EvertonAgner:对窗口使用唯一的名称,它将作为_blank
Guffa

62

由于您希望整个表单都包含在javascript中,因此无需在标签中编写表单,您可以执行以下操作:

var form = document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("action", "openData.do");

form.setAttribute("target", "view");

var hiddenField = document.createElement("input"); 
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", "message");
hiddenField.setAttribute("value", "val");
form.appendChild(hiddenField);
document.body.appendChild(form);

window.open('', 'view');

form.submit();

5
没有基于jQuery和纯JavaScript的实现。谢谢。
Pawan Pillai 2014年

2
@Mercenary页面在此处的新选项卡中打开,我可以在新的弹出窗口中打开页面吗?
Yaje 2014年

29

即使我迟到了3年,但为简化Guffa的示例,您甚至根本不需要在页面上填写表格:

$('<form method="post" action="test.asp" target="TheWindow">
       <input type="hidden" name="something" value="something">
       ...
   </form>').submit();

编辑:

$('<form method="post" action="test.asp" target="TheWindow">
       <input type="hidden" name="something" value="something">
       ...
   </form>').appendTo('body').submit().remove();

也许对某人有用的提示:)


7
该解决方案是不完整的。它应该首先添加此表单正文,然后提交。所以说.submit(); 它应该说.appendTo('body')。submit();
Jonathan van de Veen 2014年

1
如果没有这部分$("body").append(form);将无法正常工作
阿克塞尔

4
如果.remove()在Jonathan的建议之后添加.appendTo('body').submit(),您甚至会自己清理一下,而不用表单对象使当前页面混乱。
西蒙(Simon)

24

我完全同意上面发布的雇佣兵的回答,并为我创建了此功能,该功能对我有用。这不是答案,而是雇佣军对以上帖子的评论

function openWindowWithPostRequest() {
  var winName='MyWindow';
  var winURL='search.action';
  var windowoption='resizable=yes,height=600,width=800,location=0,menubar=0,scrollbars=1';
  var params = { 'param1' : '1','param2' :'2'};         
  var form = document.createElement("form");
  form.setAttribute("method", "post");
  form.setAttribute("action", winURL);
  form.setAttribute("target",winName);  
  for (var i in params) {
    if (params.hasOwnProperty(i)) {
      var input = document.createElement('input');
      input.type = 'hidden';
      input.name = i;
      input.value = params[i];
      form.appendChild(input);
    }
  }              
  document.body.appendChild(form);                       
  window.open('', winName,windowoption);
  form.target = winName;
  form.submit();                 
  document.body.removeChild(form);           
}

12

您可以简单地target="_blank"在表格上使用。

<form action="action.php" method="post" target="_blank">
    <input type="hidden" name="something" value="some value">
</form>

以您喜欢的方式添加隐藏的输入,然后只需使用JS提交表单即可。


此外,由于window.open如果未在click处理程序中调用(或任何类似的由用户触发的事件),则将作为弹出窗口被阻止
Xenos

4

我创建了一个函数来生成表单,该表单基于url,目标和作为POST/ GETdata和Submit方法的对象。它支持该对象内的嵌套和混合类型,因此可以完全复制您提供给它的任何结构:PHP自动对其进行解析并将其作为嵌套数组返回。但是,有一个限制:方括号[and ]不能成为对象中任何键的一部分(例如{"this [key] is problematic" : "hello world"})。如果有人知道如何正确逃脱,请告诉!

事不宜迟,以下是来源:

用法示例:

document.body.onclick = function() {
  var obj = {
    "a": [1, 2, [3, 4]],
    "b": "a",
    "c": {
      "x": [1],
      "y": [2, 3],
      "z": [{
        "a": "Hello",
        "b": "World"
      }, {
        "a": "Hallo",
        "b": "Welt"
      }]
    }
  };

  var form = getForm("http://example.com", "_blank", obj, "post");

  document.body.appendChild(form);
  form.submit();
  form.parentNode.removeChild(form);
}


糟糕,用法示例中的网址格式错误。如果已修复,则不会再有错误。
仪式

1
似乎还是坏了,我的页面空白。
亚当·帕金

2

我找到了一种将参数传递到弹出窗口甚至从中检索参数的更好方法:

在主页中:

var popupwindow;
var sharedObject = {};

function openPopupWindow()
{
   // Define the datas you want to pass
   sharedObject.var1 = 
   sharedObject.var2 = 
   ...

   // Open the popup window
   window.open(URL_OF_POPUP_WINDOW, NAME_OF_POPUP_WINDOW, POPUP_WINDOW_STYLE_PROPERTIES);
   if (window.focus) { popupwindow.focus(); }
}

function closePopupWindow()
{
    popupwindow.close();

    // Retrieve the datas from the popup window
    = sharedObject.var1;
    = sharedObject.var2;
    ...
}

在弹出窗口中:

var sharedObject = window.opener.sharedObject;

// function you have to to call to close the popup window
function myclose()
{
    //Define the parameters you want to pass to the main calling window
    sharedObject.var1 = 
    sharedObject.var2 = 
    ...
    window.opener.closePopupWindow();
}

而已 !

这非常方便,因为:

  • 您不必在弹出窗口的URL中设置参数。
  • 没有表格可以定义
  • 您甚至可以使用无限参数甚至对象。
  • 双向:您可以传递参数,并且,如果需要,可以检索新参数。
  • 非常容易实现。

玩得开心!


注意:window.opener并非所有浏览器都支持。
猛禽

1

我想在React中使用纯Js和fetch polyfill做到这一点。OP并没有说他特别想创建一个表单并在其上调用Submit方法,因此我通过将表单值发布为json来完成了此操作:

examplePostData = {
    method: 'POST',
    headers: {
       'Content-type' : 'application/json',
       'Accept' : 'text/html'
    },
    body: JSON.stringify({
        someList: [1,2,3,4],
        someProperty: 'something',
        someObject: {some: 'object'}
    })
}

asyncPostPopup = () => {

    //open a new window and set some text until the fetch completes
    let win=window.open('about:blank')
    writeToWindow(win,'Loading...')

    //async load the data into the window
    fetch('../postUrl', this.examplePostData)
    .then((response) => response.text())
    .then((text) => writeToWindow(win,text))
    .catch((error) => console.log(error))
}

writeToWindow = (win,text) => {
    win.document.open()
    win.document.write(text)
    win.document.close()
}


0

我过去曾经使用过,因为我们通常使用剃刀语法进行编码

@using (Html.BeginForm("actionName", "controllerName", FormMethod.Post, new { target = "_blank" }))

{

//在此处添加隐藏和提交的表单

}

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.