窗口。通过post方法打开和传递参数。

时间:2022-03-18 15:16:31

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. This is my code:

与窗口。打开方法,我打开新的网站参数,我必须通过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>  

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

但是,当我点击这个按钮,网站测试。asp是空的(当然我尝试获得通过值- Request.Form(“b”))。

How could I solve this problem, why I can't get pass values?

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

9 个解决方案

#1


91  

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.

注意:我修改了与表单名称相关的参数名称,以显示它们不必相同。通常,您会让它们保持相似,以便更简单地跟踪值。

#2


40  

Since you wanted the whole form inside the javascript, instead of writing it in tags, you can do this:

因为你想要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();

#3


17  

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

Maybe a helpful tip for someone :)

也许给某人一个有用的提示:)

#4


13  

I completely agree with mercenary's answer posted above and created this function for me which works for me. 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);           
}

#5


6  

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提交表单。

#6


2  

I created a function to generate a form, based on url, target and an object as the POST/GET data and submit method. 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. 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"}). If someone knows how to escape it properly, please do tell!

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

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:

使用的例子:

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

#7


1  

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.
  • 您可以使用illimited参数甚至对象。
  • Bi-directionnal : you can pass parameters AND, if you want you, can retreive new parameters.
  • 双向的:您可以传递参数,如果您需要,可以重新设置新的参数。
  • Very easy to implement.
  • 非常容易实现。

Have Fun!

玩得开心!

#8


0  

The default submit Action is Ext.form.action.Submit, which uses an Ajax request to submit the form's values to a configured URL. To enable normal browser submission of an Ext form, use the standardSubmit config option.

默认的submit操作是Ext.form.action。提交,它使用Ajax请求将表单的值提交到已配置的URL。要使普通浏览器提交一个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. Hope that this will help you :)

解决方案:将标准提交:true在您的配置中。希望这对你有帮助:)

#9


0  

I wanted to do this in React using plain Js and the 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:

我想用普通的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()
}

#1


91  

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.

注意:我修改了与表单名称相关的参数名称,以显示它们不必相同。通常,您会让它们保持相似,以便更简单地跟踪值。

#2


40  

Since you wanted the whole form inside the javascript, instead of writing it in tags, you can do this:

因为你想要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();

#3


17  

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

Maybe a helpful tip for someone :)

也许给某人一个有用的提示:)

#4


13  

I completely agree with mercenary's answer posted above and created this function for me which works for me. 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);           
}

#5


6  

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提交表单。

#6


2  

I created a function to generate a form, based on url, target and an object as the POST/GET data and submit method. 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. 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"}). If someone knows how to escape it properly, please do tell!

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

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:

使用的例子:

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

#7


1  

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.
  • 您可以使用illimited参数甚至对象。
  • Bi-directionnal : you can pass parameters AND, if you want you, can retreive new parameters.
  • 双向的:您可以传递参数,如果您需要,可以重新设置新的参数。
  • Very easy to implement.
  • 非常容易实现。

Have Fun!

玩得开心!

#8


0  

The default submit Action is Ext.form.action.Submit, which uses an Ajax request to submit the form's values to a configured URL. To enable normal browser submission of an Ext form, use the standardSubmit config option.

默认的submit操作是Ext.form.action。提交,它使用Ajax请求将表单的值提交到已配置的URL。要使普通浏览器提交一个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. Hope that this will help you :)

解决方案:将标准提交:true在您的配置中。希望这对你有帮助:)

#9


0  

I wanted to do this in React using plain Js and the 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:

我想用普通的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()
}