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

时间:2010-10-17 02:34:43

标签: javascript

使用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"))。

我怎么能解决这个问题,为什么我无法获得传递值?

10 个答案:

答案 0 :(得分:105)

不是将表单写入新窗口(通过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');

注意:我改变了与表单名称相关的参数名称,以表明它们不必相同。通常你会让它们彼此相似,以便更容易跟踪这些值。

答案 1 :(得分:48)

由于你想在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();

答案 2 :(得分:19)

即使我迟到了3年,但为了简化Guffa的例子,你根本不需要在页面上有表格:

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

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

答案 3 :(得分:15)

我完全同意上面发布的mercenary的答案,并为我创建了适用于我的这个功能。这不是答案,而是mercenary

对上述帖子的评论
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);           
}

答案 4 :(得分:11)

您只需在表单上使用target="_blank"即可。

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

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

答案 5 :(得分:2)

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

不用多说,这里是来源:

function getForm(url, target, values, method) {
  function grabValues(x) {
    var path = [];
    var depth = 0;
    var results = [];

    function iterate(x) {
      switch (typeof x) {
        case 'function':
        case 'undefined':
        case 'null':
          break;
        case 'object':
          if (Array.isArray(x))
            for (var i = 0; i < x.length; i++) {
              path[depth++] = i;
              iterate(x[i]);
            }
          else
            for (var i in x) {
              path[depth++] = i;
              iterate(x[i]);
            }
          break;
        default:
          results.push({
            path: path.slice(0),
            value: x
          })
          break;
      }
      path.splice(--depth);
    }
    iterate(x);
    return results;
  }
  var form = document.createElement("form");
  form.method = method;
  form.action = url;
  form.target = target;

  var values = grabValues(values);

  for (var j = 0; j < values.length; j++) {
    var input = document.createElement("input");
    input.type = "hidden";
    input.value = values[j].value;
    input.name = values[j].path[0];
    for (var k = 1; k < values[j].path.length; k++) {
      input.name += "[" + values[j].path[k] + "]";
    }
    form.appendChild(input);
  }
  return form;
}

用法示例:

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

答案 6 :(得分:1)

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

在主页:

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中设置参数。
  • 没有要定义的表单
  • 您甚至可以使用带有参数的参数。
  • 双向:您可以传递参数AND,如果需要,可以检索新参数。
  • 非常容易实施。

玩得开心!

答案 7 :(得分:0)

默认提交操作是Ext.form.action.Submit,它使用Ajax请求将表单的值提交到已配置的URL。要启用Ext表单的正常浏览器提交,请使用standardSubmit配置选项。

链接:http://docs.sencha.com/extjs/4.2.1/#!/api/Ext.form.Basic-cfg-standardSubmit

解决方案:在您的配置中输入standardSubmit:true。希望这会对你有所帮助:)。

答案 8 :(得分:0)

我想在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()
}

答案 9 :(得分:0)

由于我们通常使用剃刀语法进行编码,因此我过去一直在使用它

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

{

///在此处添加隐藏文件和表单

}

相关问题