Window.open 및 post 메소드로 매개 변수 전달
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")
).
이 문제를 어떻게 해결할 수 있으며 통과 값을 얻을 수없는 이유는 무엇입니까?
새 창에 양식을 작성하는 대신 (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');
.
참고 : 양식 이름과 관련하여 매개 변수 이름을 변경하여 동일 할 필요가 없음을 보여주었습니다. 일반적으로 값을 더 쉽게 추적 할 수 있도록 서로 유사하게 유지합니다.
태그로 작성하는 대신 자바 스크립트 안에 전체 양식을 원했기 때문에 다음과 같이 할 수 있습니다.
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 년 늦었지만 Guffa의 예를 단순화하기 위해 페이지에 양식이 전혀 필요하지 않습니다.
$('<form method="post" action="test.asp" target="TheWindow">
<input type="hidden" name="something" value="something">
...
</form>').submit();
누군가에게 도움이 될 수있는 팁 :)
나는 위에 게시 된 용병 의 답변에 완전히 동의하고 나를 위해 작동하는이 기능을 만들었습니다. 답이 아니라 위 글에 대한 용병 의 댓글
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);
}
target="_blank"
양식에 간단히 사용할 수 있습니다 .
<form action="action.php" method="post" target="_blank">
<input type="hidden" name="something" value="some value">
</form>
원하는 방식으로 숨겨진 입력을 추가 한 다음 JS로 양식을 제출하면됩니다.
팝업 창에 매개 변수를 전달하고 매개 변수를 검색하는 더 좋은 방법을 찾았습니다.
메인 페이지에서 :
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에 매개 변수를 설정하지 않아도됩니다.
- 정의 할 양식이 없습니다.
- 무제한 매개 변수를 객체에도 사용할 수 있습니다.
- 양방향 : 매개 변수를 전달할 수 있으며 원하는 경우 새 매개 변수를 검색 할 수 있습니다.
- 구현하기 매우 쉽습니다.
즐기세요!
URL, 대상 및 객체를 POST
/ GET
데이터 및 제출 방법 으로 기반으로 양식을 생성하는 함수를 만들었습니다 . 해당 객체 내에서 중첩 및 혼합 유형을 지원하므로 사용자가 제공하는 모든 구조를 완전히 복제 할 수 있습니다. PHP는 자동으로 구문 분석하고 중첩 된 배열로 반환합니다. 그러나 한 가지 제한이 있습니다. 대괄호 [
및 ]
객체의 키에 포함되지 않아야합니다 (예 {"this [key] is problematic" : "hello world"}
:). 누군가가 제대로 탈출하는 방법을 알고 있다면 알려주세요!
더 이상 고민하지 않고 소스는 다음과 같습니다.
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;
}
사용 예 :
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);
}
기본 제출 작업은 Ext.form.action.Submit이며, Ajax 요청을 사용하여 구성된 URL에 양식 값을 제출합니다. Ext 양식의 일반 브라우저 제출을 사용하려면 standardSubmit 구성 옵션을 사용하십시오.
Link: 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 :)
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:
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()
}
I've used this in the past, since we typically use razor syntax for coding
@using (Html.BeginForm("actionName", "controllerName", FormMethod.Post, new { target = "_blank" }))
{
// add hidden and form filed here
}
참고URL : https://stackoverflow.com/questions/3951768/window-open-and-pass-parameters-by-post-method
'Nice programing' 카테고리의 다른 글
ReactJS의 동적 속성 (0) | 2020.10.06 |
---|---|
Swift에서 UIAlertController에 TextField를 추가하는 방법 (0) | 2020.10.06 |
C #에서 DateTime 개체를 어떻게 복제 할 수 있습니까? (0) | 2020.10.06 |
Android에서 String.isEmpty ()를 호출 할 수 없습니다. (0) | 2020.10.06 |
비 유형 템플릿 매개 변수 (0) | 2020.10.06 |