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

luk*_*443 84 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>  
Run Code Online (Sandbox Code Playgroud)

接下来,我创建数组:

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

并调用函数:

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

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

我怎么能解决这个问题,为什么我不能得到传递值?

Guf*_*ffa 112

而不是将表单写入新窗口(通过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>
Run Code Online (Sandbox Code Playgroud)

编辑:

要动态设置表单中的值,您可以这样做:

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();
}
Run Code Online (Sandbox Code Playgroud)

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

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

  • @EvertonAgner:为窗口使用唯一的名称,它将作为“_blank”工作。 (2认同)

Mer*_*ary 54

既然你想在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();
Run Code Online (Sandbox Code Playgroud)

  • 没有基于jQuery和Pure JavaScript的实现.谢谢. (4认同)
  • @Mercenary页面在新标签页面中打开,我可以在新的弹出窗口中打开页面吗? (2认同)

And*_*ius 21

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

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

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

  • 这个解决方案不完整.它应该首先添加此形式的身体,然后提交它.所以在哪里说.submit(); 它应该说.appendTo('body').submit(); (6认同)
  • 没有这部分 `$("body").append(form);` 它将无法工作 (2认同)
  • 如果在乔纳森(Jonathan)建议的.appendTo('body')。submit()`之后添加`.remove()`,您甚至会自己清理干净,而不会使表单对象显得混乱。 (2认同)

小智 17

我完全同意上面发布的雇佣兵的答案,并为我创造了这个功能对我有用.这不是答案,而是雇佣军对上述帖子的评论

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);           
}
Run Code Online (Sandbox Code Playgroud)


Pie*_*ier 11

你可以简单地target="_blank"在表格上使用.

<form action="action.php" method="post" target="_blank">
    <input type="hidden" name="something" value="some value">
</form>
Run Code Online (Sandbox Code Playgroud)

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


Cer*_*ony 6

我创建了一个函数来生成一个表单,基于 url、目标和一个对象作为POST/GET数据和提交方法。它支持该对象内的嵌套和混合类型,因此它可以完全复制您提供给它的任何结构: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;
}
Run Code Online (Sandbox Code Playgroud)

用法示例:

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);
Run Code Online (Sandbox Code Playgroud)