Window.open 및 post 메소드로 매개 변수 전달


97

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

이 문제를 어떻게 해결할 수 있습니까? 왜 합격 값을 얻을 수 없습니까?


2
작동하지 않는 것은 무엇입니까? jsfiddle.net/TZMMF에 사본을 저장했는데 예상대로 작동합니다.
PleaseStand

답변 감사합니다. 예, 죄송합니다-위의 코드가 작동합니다. 하지만 키 배열로이 함수를 테스트합니다. <script type = "text / javascript"> var values ​​= new Array ( "value1", "value2", "value3") var keys = new Array ( "1", "2 ","3 ") // a, b, c 대신 </ script> Request.Form ("2 ")으로 값을 얻습니다. IE와 Firefox에서는 빈 페이지가 나타납니다.
luk4443

답변:


121

새 창에 양식을 작성하는 대신 (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');.

참고 : 양식 이름과 관련하여 매개 변수 이름을 변경하여 동일 할 필요가 없음을 보여주었습니다. 일반적으로 값을 더 쉽게 추적 할 수 있도록 서로 유사하게 유지합니다.


그것이 바로 제가 생각했던 것입니다. 게시 된 원래 코드는 IE를 제외하고는 작동하는 것처럼 보였습니다.
PleaseStand

답변 감사합니다. 하지만 열에 버튼이있는 테이블이 있습니다. 이 버튼을 클릭하면 새 페이지를 열고 일부 매개 변수를 전달합니다. 그래서 함수를 작성하고 각 버튼에 대해 호출하고 고정 인수를 전달해야합니다. 내 질문, 위의 코드를 어떻게 다시 작성할 수 있습니까?
luk4443

1
@ luk4443 : 창을 열 때 URL을 사용하면 양식을 게시 할 때 페이지가 바뀝니다. action양식 의 속성에 URL을 입력합니다 .
Guffa

1
@Guffa의 동작을 시뮬레이션하는 방법은 target="_blank"무엇입니까?
everton

2
@EvertonAgner : 창에 고유 한 이름을 사용하면 _blank.
Guffa 2015

62

태그로 작성하는 대신 자바 스크립트 안에 전체 양식을 원했기 때문에 다음과 같이 할 수 있습니다.

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

5
jQuery 및 Pure JavaScript 기반 구현이 없습니다. 감사.
Pawan Pillai 2014 년

2
@ 용병 페이지가 여기에 새 탭에서 열립니다. 새 팝업 창에서 페이지를 열 수 있나요?
Yaje 2014

29

내가 3 년 늦었지만 Guffa의 예를 단순화하기 위해 페이지에 양식이 전혀 필요하지도 않습니다.

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

편집 :

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

누군가에게 도움이 될 수있는 팁 :)


7
이 솔루션은 불완전합니다. 먼저이 양식을 본문에 추가 한 다음 제출해야합니다. 그래서 그것이 .submit (); .appendTo ( 'body'). submit ();
Jonathan van de Veen 2014

1
이 부분 $("body").append(form);이 없으면 작동하지 않습니다
Axel

4
.remove()Jonathan이 제안한 뒤에 를 추가하면 .appendTo('body').submit()자신을 정리하고 현재 페이지를 양식 객체로 어지럽히 지 않습니다.
사이먼

24

나는 위에 게시 된 용병 의 답변에 완전히 동의하고 나를 위해 작동하는이 기능을 만들었습니다. 답이 아니라 위 게시물에 대한 용병 의 댓글입니다.

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

12

target="_blank"양식에 간단히 사용할 수 있습니다 .

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

원하는 방식으로 숨겨진 입력을 추가 한 다음 JS로 양식을 제출하면됩니다.


또한 이후 window.open팝업으로 차단 될 것입니다하는 내에서 호출하지 않을 경우 click핸들러 (또는 사용자가 같은 이벤트 해고)
Xenos

4

URL, 대상 및 객체를 POST/ GET데이터 및 제출 방법 으로 기반으로 양식을 생성하는 함수를 만들었습니다 . 해당 객체 내에서 중첩 및 혼합 유형을 지원하므로 사용자가 제공하는 모든 구조를 완전히 복제 할 수 있습니다. PHP는 자동으로 구문 분석하고 중첩 된 배열로 반환합니다. 그러나 한 가지 제한이 있습니다. 대괄호 []객체의 키의 일부가 아니어야합니다 (예 {"this [key] is problematic" : "hello world"}:). 누군가가 제대로 탈출하는 방법을 알고 있다면 알려주십시오!

더 이상 고민하지 않고 소스는 다음과 같습니다.

사용 예 :

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


죄송합니다. 사용 예의 URL 형식이 잘못되었습니다. 수정하면 더 이상 오류가 없습니다.
행사

1
여전히 깨진 것 같습니다. 빈 페이지가 표시됩니다.
Adam Parkin

2

팝업 창에 매개 변수를 전달하고 매개 변수를 검색하는 더 좋은 방법을 찾았습니다.

메인 페이지에서 :

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

팝업 창에서 :

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

그게 다야!

다음과 같은 이유로 매우 편리합니다.

  • 팝업 창의 URL에 매개 변수를 설정하지 않아도됩니다.
  • 정의 할 양식이 없습니다.
  • 무제한 매개 변수를 객체에도 사용할 수 있습니다.
  • 양방향 : 매개 변수를 전달할 수 있으며 원하는 경우 새 매개 변수를 검색 할 수 있습니다.
  • 구현하기가 매우 쉽습니다.

즐기세요!


참고 : window.opener모든 브라우저에서 지원되는 것은 아닙니다.
Raptor

1

나는 일반 Js와 fetch polyfill을 사용하여 React에서 이것을하고 싶었 습니다 . OP는 구체적으로 양식을 작성하고 제출 메소드를 호출하고 싶다고 말하지 않았으므로 양식 값을 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()
}

0

기본 제출 조치는 Ext.form.action.Submit이며 Ajax 요청을 사용하여 구성된 URL에 양식 값을 제출합니다. Ext 양식의 일반 브라우저 제출을 사용하려면 standardSubmit 구성 옵션을 사용하십시오.

링크 : http://docs.sencha.com/extjs/4.2.1/#!/api/Ext.form.Basic-cfg-standardSubmit

솔루션 : 구성에 standardSubmit : true를 넣으십시오. 이것이 당신을 도울 수 있기를 바랍니다 :)


0

우리는 일반적으로 코딩에 면도기 구문을 사용하기 때문에 과거에 이것을 사용했습니다.

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

{

// 여기에 숨겨진 양식 및 양식 추가

}

당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.