小编典典

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

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

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


阅读 3142

收藏
2020-05-01

共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');

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

2020-05-01