简体   繁体   English

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

[英]Window.open and pass parameters by post method

With window.open method I open new site with parameters, which I have to pass by post method.I've found solution, but unfortunately it doesn't work.使用 window.open 方法,我打开带有参数的新站点,我必须通过 post 方法传递这些参数。我找到了解决方案,但不幸的是它不起作用。 This is my code:这是我的代码:

<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>  

Next, I create arrays:接下来,我创建数组:

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

And call function by:并通过以下方式调用函数:

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

But, when I click on this button, the site test.asp is empty (of course I try get pass values - Request.Form("b") ).但是,当我单击此按钮时,站点 test.asp 是空的(当然我尝试获取传递值 - Request.Form("b") )。

How could I solve this problem, why I can't get pass values?我该如何解决这个问题,为什么我无法获得传递值?

Instead of writing a form into the new window (which is tricky to get correct, with encoding of values in the HTML code), just open an empty window and post a form to it.无需将表单写入新窗口(这很难正确正确,在 HTML 代码中对值进行编码),只需打开一个空窗口并向其发送表单即可。

Example:例子:

<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>

Edit:编辑:

To set the values in the form dynamically, you can do like this:要动态设置表单中的值,您可以这样做:

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

To post the form you call the function with the values, like openWindowWithPost('a','b','c');要发布表单,请使用值调用函数,例如openWindowWithPost('a','b','c'); . .

Note: I varied the parameter names in relation to the form names to show that they don't have to be the same.注意:我改变了与表单名称相关的参数名称,以表明它们不必相同。 Usually you would keep them similar to each other to make it simpler to track the values.通常,您会使它们彼此相似,以便更轻松地跟踪值。

Since you wanted the whole form inside the javascript, instead of writing it in tags, you can do this:由于您希望在 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();

I completely agree with mercenary 's answer posted above and created this function for me which works for me.我完全同意上面发布的mercenary的回答,并为我创建了这个对我有用的功能。 It's not an answer, it's a comment on above post by 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);           
}

Even though I am 3 years late, but to simplify Guffa's example, you don't even need to have the form on the page at all:尽管我迟到了 3 年,但为了简化 Guffa 的示例,您甚至根本不需要页面上的表单:

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

Edited:编辑:

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

Maybe a helpful tip for someone :)也许对某人有用的提示:)

You could simply use target="_blank" on the form.您可以简单地在表单上使用target="_blank"

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

Add hidden inputs in the way you prefer, and then simply submit the form with JS.以您喜欢的方式添加隐藏输入,然后只需使用 JS 提交表单。

I created a function to generate a form, based on url, target and an object as the POST / GET data and submit method.我创建了一个函数来生成一个表单,基于 url、目标和一个对象作为POST / GET数据和提交方法。 It supports nested and mixed types within that object, so it can fully replicate any structure you feed it: PHP automatically parses it and returns it as a nested array.它支持该对象内的嵌套和混合类型,因此它可以完全复制您提供给它的任何结构:PHP 自动解析它并将其作为嵌套数组返回。 However, there is a single restriction: the brackets [ and ] must not be part of any key in the object (like {"this [key] is problematic" : "hello world"} ).但是,有一个限制:方括号[]不能是对象中任何键的一部分(例如{"this [key] is problematic" : "hello world"} )。 If someone knows how to escape it properly, please do tell!如果有人知道如何正确逃脱它,请告诉!

Without further ado, here is the source:废话不多说,源码如下:

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

Usage example:用法示例:

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

I found a better way to pass parameters to the popup window and even to retrieve parameters from it :我找到了一种将参数传递给弹出窗口甚至从中检索参数的更好方法:

In the main page :在主页面:

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

In the popup window :在弹出窗口中:

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

That's it !而已 !

And this is very convenient because:这非常方便,因为:

  • You have not to set parameters in the URL of the popup window.您不必在弹出窗口的 URL 中设置参数。
  • No form to define没有定义的形式
  • You can use illimited parameters even objects.您可以使用无限参数甚至对象。
  • Bi-directionnal : you can pass parameters AND, if you want you, can retreive new parameters. Bi-directionnal :您可以传递参数,如果需要,还可以检索新参数。
  • Very easy to implement.非常容易实施。

Have Fun!玩得开心!

I wanted to do this in React using plain Js and the fetch polyfill .我想在 React 中使用普通的 Js 和 fetch polyfill来做到这一点。 OP didn't say he specifically wanted to create a form and invoke the submit method on it, so I have done it by posting the form values as json: 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()
}

The default submit Action is Ext.form.action.Submit, which uses an Ajax request to submit the form's values to a configured URL.默认提交操作是 Ext.form.action.Submit,它使用 Ajax 请求将表单的值提交到配置的 URL。 To enable normal browser submission of an Ext form, use the standardSubmit config option.要启用 Ext 表单的正常浏览器提交,请使用标准提交配置选项。

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

solution: put standardSubmit :true in your config.解决方案:将 standardSubmit :true 放入您的配置中。 Hope that this will help you :)希望这会帮助你:)

I've used this in the past, since we typically use razor syntax for coding我过去使用过这个,因为我们通常使用 razor 语法进行编码

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

{ {

// add hidden and form filed here // 在此处添加隐藏和表单提交

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM