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

2022-08-30 04:39:30

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

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

我该如何解决这个问题,为什么我无法获得传递值?


答案 1

与其将表单写入新窗口(使用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');

注意:我根据表单名称更改了参数名称,以表明它们不必相同。通常,您会使它们彼此相似,以便更轻松地跟踪值。


答案 2

由于您希望将整个表单放在javascript中,因此您可以这样做,而不是将其写入标签中:

let windowName = 'w_' + Date.now() + Math.floor(Math.random() * 100000).toString();
var form = document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("action", "openData.do");

form.setAttribute("target", windowName);

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('', windowName);

form.submit();