폼 제출과 같은 JavaScript 투고 요청
브라우저를 다른 페이지로 이동하려고 합니다.GET 요청을 원했다면 이렇게 말할 수 있습니다.
document.location.href = 'http://example.com/q=a';
그러나 POST 요청을 사용하지 않으면 액세스하려는 리소스가 제대로 응답하지 않습니다.이것이 동적으로 생성되지 않았다면 HTML을 사용할 수 있습니다.
<form action="http://example.com/" method="POST">
<input type="hidden" name="q" value="a">
</form>
그럼 DOM에서 양식을 제출하겠습니다.
하지만 정말로 나는 내가 말할 수 있는 자바스크립트 코드를 원한다.
post_to_url('http://example.com/', {'q':'a'});
최적의 크로스 브라우저 구현은 무엇입니까?
편집
이해가 안 돼서 미안해.양식을 제출하는 것처럼 브라우저의 위치를 변경하는 솔루션이 필요합니다.이것이 XMLHttpRequest에서 가능한 경우 명확하지 않습니다.비동기화도 XML을 사용해도 안 되기 때문에 Ajax는 답이 아닙니다.
「」를 한다.<input>
을 갖추어 제출하다
/**
* sends a request to the specified url from a form. this will change the window location.
* @param {string} path the path to send the post request to
* @param {object} params the parameters to add to the url
* @param {string} [method=post] the method to use on the form
*/
function post(path, params, method='post') {
// The rest of this code assumes you are not using a library.
// It can be made less verbose if you use one.
const form = document.createElement('form');
form.method = method;
form.action = path;
for (const key in params) {
if (params.hasOwnProperty(key)) {
const hiddenField = document.createElement('input');
hiddenField.type = 'hidden';
hiddenField.name = key;
hiddenField.value = params[key];
form.appendChild(hiddenField);
}
}
document.body.appendChild(form);
form.submit();
}
예를 들어:
post('/contact/', {name: 'Johnny Bravo'});
EDIT:이것이 매우 높은 투표율을 보이고 있기 때문에, 카피 페이스트에 의한 투고가 많아질 것이라고 생각합니다.그래서 제가...hasOwnProperty
부주의한 버그를 수정하기 위해 체크합니다.
이것은 jQuery를 사용하여 선택한 답변의 버전입니다.
// Post to the provided URL with the specified parameters.
function post(path, parameters) {
var form = $('<form></form>');
form.attr("method", "post");
form.attr("action", path);
$.each(parameters, function(key, value) {
var field = $('<input></input>');
field.attr("type", "hidden");
field.attr("name", key);
field.attr("value", value);
form.append(field);
});
// The form needs to be a part of the document in
// order for us to be able to submit it.
$(document.body).append(form);
form.submit();
}
@Aaron의 간단한 구현:
document.body.innerHTML += '<form id="dynForm" action="http://example.com/" method="post"><input type="hidden" name="q" value="a"></form>';
document.getElementById("dynForm").submit();
물론 프로토타입이나 jQuery와 같은 JavaScript 프레임워크를 사용해야 합니다.
「 」의 createElement
이 답변에서 제공되는 함수는 정상적으로 생성된 요소의 이름 속성과 IE의 파손으로 인해 필요합니다.document.createElement
:
function postToURL(url, values) {
values = values || {};
var form = createElement("form", {action: url,
method: "POST",
style: "display: none"});
for (var property in values) {
if (values.hasOwnProperty(property)) {
var value = values[property];
if (value instanceof Array) {
for (var i = 0, l = value.length; i < l; i++) {
form.appendChild(createElement("input", {type: "hidden",
name: property,
value: value[i]}));
}
}
else {
form.appendChild(createElement("input", {type: "hidden",
name: property,
value: value}));
}
}
}
document.body.appendChild(form);
form.submit();
document.body.removeChild(form);
}
Rakesh Pai의 답변은 훌륭하지만, (Safari에서) 라는 필드가 있는 폼을 올리려고 하면 문제가 발생합니다.submit
를 들어.post_to_url("http://google.com/",{ submit: "submit" } );
이 가변공간 충돌을 우회하기 위해 기능을 약간 패치했습니다.
function post_to_url(path, params, method) {
method = method || "post";
var form = document.createElement("form");
//Move the submit function to another variable
//so that it doesn't get overwritten.
form._submit_function_ = form.submit;
form.setAttribute("method", method);
form.setAttribute("action", path);
for(var key in params) {
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", key);
hiddenField.setAttribute("value", params[key]);
form.appendChild(hiddenField);
}
document.body.appendChild(form);
form._submit_function_(); //Call the renamed function.
}
post_to_url("http://google.com/", { submit: "submit" } ); //Works!
아니요. JavaScript 게시 요청은 폼 제출과 같이 할 수 없습니다.
HTML 형식의 폼을 가지고 JavaScript와 함께 제출하면 됩니다.(이 페이지에서 여러 번 설명한 바와 같이).
HTML을 직접 만들 수 있고 HTML을 작성하기 위해 자바스크립트가 필요하지 않습니다. 만약 사람들이 그것을 제안한다면 그것은 어리석은 것입니다.
<form id="ninja" action="http://example.com/" method="POST">
<input id="donaldduck" type="hidden" name="q" value="a">
</form>
사용자의 함수는 원하는 대로 폼을 구성합니다.
function postToURL(a,b,c){
document.getElementById("ninja").action = a;
document.getElementById("donaldduck").name = b;
document.getElementById("donaldduck").value = c;
document.getElementById("ninja").submit();
}
그럼 이렇게 쓰세요.
postToURL("http://example.com/","q","a");
하지만 저는 그 기능을 생략하고 그냥 할 것입니다.
document.getElementById('donaldduck').value = "a";
document.getElementById("ninja").submit();
마지막으로 스타일 결정은 ccs 파일로 진행됩니다.
#ninja{
display:none;
}
개인적으로 나는 양식이 이름으로 불려져야 한다고 생각하지만 그것은 지금 당장은 중요하지 않다.
이는 rakesh의 답변이지만 어레이에 대한 지원(형식은 매우 일반적입니다)을 통해 다음과 같습니다.
플레인 javascript:
function post_to_url(path, params, method) {
method = method || "post"; // Set method to post by default, if not specified.
// The rest of this code assumes you are not using a library.
// It can be made less wordy if you use one.
var form = document.createElement("form");
form.setAttribute("method", method);
form.setAttribute("action", path);
var addField = function( key, value ){
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", key);
hiddenField.setAttribute("value", value );
form.appendChild(hiddenField);
};
for(var key in params) {
if(params.hasOwnProperty(key)) {
if( params[key] instanceof Array ){
for(var i = 0; i < params[key].length; i++){
addField( key, params[key][i] )
}
}
else{
addField( key, params[key] );
}
}
}
document.body.appendChild(form);
form.submit();
}
아, 여기 jquery 버전이 있습니다. (다른 코드를 사용하지만, 같은 것으로 요약됩니다.)
function post_to_url(path, params, method) {
method = method || "post"; // Set method to post by default, if not specified.
var form = $(document.createElement( "form" ))
.attr( {"method": method, "action": path} );
$.each( params, function(key,value){
$.each( value instanceof Array? value : [value], function(i,val){
$(document.createElement("input"))
.attr({ "type": "hidden", "name": key, "value": val })
.appendTo( form );
});
} );
form.appendTo( document.body ).submit();
}
프로토타입을 설치한 경우 코드를 조여 다음과 같이 숨겨진 양식을 생성하고 제출할 수 있습니다.
var form = new Element('form',
{method: 'post', action: 'http://example.com/'});
form.insert(new Element('input',
{name: 'q', value: 'a', type: 'hidden'}));
$(document.body).insert(form);
form.submit();
한 가지 해결책은 양식을 생성하여 제출하는 것입니다.하나의 구현은
function post_to_url(url, params) {
var form = document.createElement('form');
form.action = url;
form.method = 'POST';
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);
}
}
form.submit();
}
그래서 간단한 URL 단축 북마크렛을 구현할 수 있습니다.
javascript:post_to_url('http://is.gd/create.php', {'URL': location.href});
글쎄, Rakesh Pai의 대답으로 이것을 만드는 데 시간을 허비하지 않고 다른 모든 게시물을 읽었으면 좋았을 텐데.다음은 어레이 및 개체와 함께 작동하는 재귀 솔루션입니다.jQuery에 의존하지 않습니다.
전체 폼을 배열처럼 제출해야 하는 경우(항목 목록 주위에 래퍼 개체가 없는 경우)를 처리하기 위해 세그먼트를 추가했습니다.
/**
* Posts javascript data to a url using form.submit().
* Note: Handles json and arrays.
* @param {string} path - url where the data should be sent.
* @param {string} data - data as javascript object (JSON).
* @param {object} options -- optional attributes
* {
* {string} method: get/post/put/etc,
* {string} arrayName: name to post arraylike data. Only necessary when root data object is an array.
* }
* @example postToUrl('/UpdateUser', {Order {Id: 1, FirstName: 'Sally'}});
*/
function postToUrl(path, data, options) {
if (options === undefined) {
options = {};
}
var method = options.method || "post"; // Set method to post by default if not specified.
var form = document.createElement("form");
form.setAttribute("method", method);
form.setAttribute("action", path);
function constructElements(item, parentString) {
for (var key in item) {
if (item.hasOwnProperty(key) && item[key] != null) {
if (Object.prototype.toString.call(item[key]) === '[object Array]') {
for (var i = 0; i < item[key].length; i++) {
constructElements(item[key][i], parentString + key + "[" + i + "].");
}
} else if (Object.prototype.toString.call(item[key]) === '[object Object]') {
constructElements(item[key], parentString + key + ".");
} else {
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", parentString + key);
hiddenField.setAttribute("value", item[key]);
form.appendChild(hiddenField);
}
}
}
}
//if the parent 'data' object is an array we need to treat it a little differently
if (Object.prototype.toString.call(data) === '[object Array]') {
if (options.arrayName === undefined) console.warn("Posting array-type to url will doubtfully work without an arrayName defined in options.");
//loop through each array item at the parent level
for (var i = 0; i < data.length; i++) {
constructElements(data[i], (options.arrayName || "") + "[" + i + "].");
}
} else {
//otherwise treat it normally
constructElements(data, "");
}
document.body.appendChild(form);
form.submit();
};
세 가지 옵션이 있습니다.
표준 JavaScript 답변:틀을 사용하세요!대부분의 Ajax 프레임워크에서는 XMLHTTPRequest POST를 쉽게 작성할 수 있습니다.
직접 XMLHTTPRequest 요청을 작성하고, get 대신 오픈 메서드로 포스트를 전달합니다.(자세한 내용은 XMLHTTPRequest(Ajax)에서의 POST 메서드 사용)
JavaScript를 사용하여 폼을 동적으로 만들고 액션을 추가하고 입력을 추가한 후 제출합니다.
나는 다른 사람들이 제안하는 대로 Ajax 루트를 따를 것이다.
var xmlHttpReq = false;
var self = this;
// Mozilla/Safari
if (window.XMLHttpRequest) {
self.xmlHttpReq = new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject) {
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpReq.open("POST", "YourPageHere.asp", true);
self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
self.xmlHttpReq.setRequestHeader("Content-length", QueryString.length);
self.xmlHttpReq.send("?YourQueryString=Value");
가장 쉬운 방법은 Ajax Post Request를 사용하는 것입니다.
$.ajax({
type: "POST",
url: 'http://www.myrestserver.com/api',
data: data,
success: success,
dataType: dataType
});
여기서:
- 데이터는 객체입니다.
- data Type은 서버에서 예상되는 데이터(xml, json, 스크립트, 텍스트, html)입니다.
- url은 RESt 서버 또는 HTTP-POST를 받아들이는 서버 측 기능의 주소입니다.
그런 다음 성공 핸들러에서 window.location과 같은 것으로 브라우저를 리디렉션합니다.
jQuery를 사용해서 이렇게 썼어요.Firefox 및 Internet Explorer에서 테스트.
function postToUrl(url, params, newWindow) {
var form = $('<form>');
form.attr('action', url);
form.attr('method', 'POST');
if(newWindow){ form.attr('target', '_blank');
}
var addParam = function(paramName, paramValue) {
var input = $('<input type="hidden">');
input.attr({ 'id': paramName,
'name': paramName,
'value': paramValue });
form.append(input);
};
// Params is an Array.
if(params instanceof Array){
for(var i=0; i<params.length; i++) {
addParam(i, params[i]);
}
}
// Params is an Associative array or Object.
if(params instanceof Object) {
for(var key in params){
addParam(key, params[key]);
}
}
// Submit the form, then remove it from the page
form.appendTo(document.body);
form.submit();
form.remove();
}
프로토타입 라이브러리에는 ".toQueryString()" 메서드를 사용하는 해시 테이블 객체가 포함되어 있으며 이를 통해 JavaScript 객체/구조를 쿼리 문자열 스타일 문자열로 쉽게 변환할 수 있습니다.게시물은 요청의 "본문"을 쿼리 문자열 형식의 문자열로 해야 하므로 Ajax 요청을 게시물로 올바르게 사용할 수 있습니다.다음은 프로토타입을 사용하는 예입니다.
$req = new Ajax.Request("http://foo.com/bar.php",{
method: 'post',
parameters: $H({
name: 'Diodeus',
question: 'JavaScript posts a request like a form request',
...
}).toQueryString();
};
내 경우 완벽하게 작동합니다.
document.getElementById("form1").submit();
다음과 같은 기능으로 사용할 수 있습니다.
function formSubmit() {
document.getElementById("frmUserList").submit();
}
이를 사용하여 입력의 모든 값을 게시할 수 있습니다.
현재 @RakeshPai에 의해 받아들여지고 있는 솔루션과는 달리, 내솔루션은 깊이 중첩된 오브젝트를 인코딩합니다.
qs' npm 라이브러리와 문자열화 함수를 사용하여 중첩된 개체를 매개 변수로 변환합니다.
이 코드는 Rails 백엔드에서 잘 작동하지만 문자열화하도록 전달된 옵션을 수정하여 필요한 백엔드와 함께 작동하도록 수정할 수 있습니다.레일에서는 arrayFormat을 "브래킷"으로 설정해야 합니다.
import qs from "qs"
function normalPost(url, params) {
var form = document.createElement("form");
form.setAttribute("method", "POST");
form.setAttribute("action", url);
const keyValues = qs
.stringify(params, { arrayFormat: "brackets", encode: false })
.split("&")
.map(field => field.split("="));
keyValues.forEach(field => {
var key = field[0];
var value = field[1];
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", key);
hiddenField.setAttribute("value", value);
form.appendChild(hiddenField);
});
document.body.appendChild(form);
form.submit();
}
예를 들어:
normalPost("/people/new", {
people: [
{
name: "Chris",
address: "My address",
dogs: ["Jordan", "Elephant Man", "Chicken Face"],
information: { age: 10, height: "3 meters" }
},
{
name: "Andrew",
address: "Underworld",
dogs: ["Doug", "Elf", "Orange"]
},
{
name: "Julian",
address: "In a hole",
dogs: ["Please", "Help"]
}
]
});
다음 레일 매개변수를 생성합니다.
{"authenticity_token"=>"...",
"people"=>
[{"name"=>"Chris", "address"=>"My address", "dogs"=>["Jordan", "Elephant Man", "Chicken Face"], "information"=>{"age"=>"10", "height"=>"3 meters"}},
{"name"=>"Andrew", "address"=>"Underworld", "dogs"=>["Doug", "Elf", "Orange"]},
{"name"=>"Julian", "address"=>"In a hole", "dogs"=>["Please", "Help"]}]}
하지만 또 다른 재귀적 해결법은, 다른 몇 가지는 고장난 것 같기 때문에(모두 테스트하지 않았습니다).이는 lodash 3.x 및 ES6에 따라 달라집니다(jQuery는 필요 없음).
function createHiddenInput(name, value) {
let input = document.createElement('input');
input.setAttribute('type','hidden');
input.setAttribute('name',name);
input.setAttribute('value',value);
return input;
}
function appendInput(form, name, value) {
if(_.isArray(value)) {
_.each(value, (v,i) => {
appendInput(form, `${name}[${i}]`, v);
});
} else if(_.isObject(value)) {
_.forOwn(value, (v,p) => {
appendInput(form, `${name}[${p}]`, v);
});
} else {
form.appendChild(createHiddenInput(name, value));
}
}
function postToUrl(url, data) {
let form = document.createElement('form');
form.setAttribute('method', 'post');
form.setAttribute('action', url);
_.forOwn(data, (value, name) => {
appendInput(form, name, value);
});
form.submit();
}
DHTML을 사용하여 폼을 동적으로 추가한 후 전송할 수 있습니다.
Form Object는 옵션입니다.그러나 FormObject는 현재 대부분의 브라우저에서 지원되지 않습니다.
이것은 Alan의 옵션 2(위)와 같습니다.httpobj를 인스턴스화하는 방법은 연습으로 남겨져 있습니다.
httpobj.open("POST", url, true);
httpobj.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');
httpobj.onreadystatechange=handler;
httpobj.send(post);
이것은 뷰에 근거하고 있습니다.SD의 코드는 jQuery를 사용합니다.오브젝트에서 재귀적으로 동작하도록 개선되었습니다.
function post(url, params, urlEncoded, newWindow) {
var form = $('<form />').hide();
form.attr('action', url)
.attr('method', 'POST')
.attr('enctype', urlEncoded ? 'application/x-www-form-urlencoded' : 'multipart/form-data');
if(newWindow) form.attr('target', '_blank');
function addParam(name, value, parent) {
var fullname = (parent.length > 0 ? (parent + '[' + name + ']') : name);
if(value instanceof Object) {
for(var i in value) {
addParam(i, value[i], fullname);
}
}
else $('<input type="hidden" />').attr({name: fullname, value: value}).appendTo(form);
};
addParam('', params, '');
$('body').append(form);
form.submit();
}
jQuery와 같은 라이브러리와 $.post 메서드를 사용할 수 있습니다.
나는 그 문서를 사용한다.는 java를 형성하고 이를 루프하여 폼 내의 모든 요소를 가져온 다음 xhttp를 통해 전송합니다.이것이 javascript / ajax submit (모든 html을 예로 포함)을 위한 저의 솔루션입니다.
<!DOCTYPE html>
<html>
<body>
<form>
First name: <input type="text" name="fname" value="Donald"><br>
Last name: <input type="text" name="lname" value="Duck"><br>
Addr1: <input type="text" name="add" value="123 Pond Dr"><br>
City: <input type="text" name="city" value="Duckopolis"><br>
</form>
<button onclick="smc()">Submit</button>
<script>
function smc() {
var http = new XMLHttpRequest();
var url = "yourphpfile.php";
var x = document.forms[0];
var xstr = "";
var ta ="";
var tb ="";
var i;
for (i = 0; i < x.length; i++) {
if (i==0){ta = x.elements[i].name+"="+ x.elements[i].value;}else{
tb = tb+"&"+ x.elements[i].name +"=" + x.elements[i].value;
} }
xstr = ta+tb;
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
// do whatever you want to with the html output response here
}
}
http.send(xstr);
}
</script>
</body>
</html>
사용자를 자동으로 다른 페이지로 전송하고 게시하는 방법은 숨겨진 양식을 작성한 후 자동으로 제출하는 것입니다.숨김 양식은 웹 페이지에서 공간을 전혀 차지하지 않습니다.코드는 다음과 같습니다.
<form name="form1" method="post" action="somepage.php">
<input name="fielda" type="text" id="fielda" type="hidden">
<textarea name="fieldb" id="fieldb" cols="" rows="" style="display:none"></textarea>
</form>
document.getElementById('fielda').value="some text for field a";
document.getElementById('fieldb').innerHTML="some text for multiline fieldb";
form1.submit();
자동 제출 적용
자동 송신 애플리케이션은, 유저가 다른 페이지에 자동적으로 삽입하는 폼 값을 그 페이지로 되돌리는 것입니다.이러한 어플리케이션은 다음과 같습니다.
fieldapost=<?php echo $_post['fielda'];>
if (fieldapost !="") {
document.write("<form name='form1' method='post' action='previouspage.php'>
<input name='fielda' type='text' id='fielda' type='hidden'>
</form>");
document.getElementById('fielda').value=fieldapost;
form1.submit();
}
내가 하는 방법은 이렇다.
function redirectWithPost(url, data){
var form = document.createElement('form');
form.method = 'POST';
form.action = url;
for(var key in data){
var input = document.createElement('input');
input.name = key;
input.value = data[key];
input.type = 'hidden';
form.appendChild(input)
}
document.body.appendChild(form);
form.submit();
}
POST 또는 GET을 사용하여 리디렉션하기 위한 jQuery 플러그인:
https://github.com/mgalante/jquery.redirect/blob/master/jquery.redirect.js
테스트하려면 위의 .js 파일을 포함하거나 클래스를 코드에 복사/붙여넣은 다음 코드를 사용하여 "args"를 변수 이름으로 바꾸고 "values"를 각 변수의 값으로 바꿉니다.
$.redirect('demo.php', {'arg1': 'value1', 'arg2': 'value2'});
위의 솔루션 중 jQuery만으로 딥 네스트된 파라미터를 처리할 수 있는 솔루션은 없습니다.다음은 저의 2센트 솔루션입니다.
jQuery를 사용하고 있고 완전 중첩된 매개변수를 처리해야 하는 경우 아래 함수를 사용할 수 있습니다.
/**
* Original code found here: https://github.com/mgalante/jquery.redirect/blob/master/jquery.redirect.js
* I just simplified it for my own taste.
*/
function postForm(parameters, url) {
// generally we post the form with a blank action attribute
if ('undefined' === typeof url) {
url = '';
}
//----------------------------------------
// SOME HELPER FUNCTIONS
//----------------------------------------
var getForm = function (url, values) {
values = removeNulls(values);
var form = $('<form>')
.attr("method", 'POST')
.attr("action", url);
iterateValues(values, [], form, null);
return form;
};
var removeNulls = function (values) {
var propNames = Object.getOwnPropertyNames(values);
for (var i = 0; i < propNames.length; i++) {
var propName = propNames[i];
if (values[propName] === null || values[propName] === undefined) {
delete values[propName];
} else if (typeof values[propName] === 'object') {
values[propName] = removeNulls(values[propName]);
} else if (values[propName].length < 1) {
delete values[propName];
}
}
return values;
};
var iterateValues = function (values, parent, form, isArray) {
var i, iterateParent = [];
Object.keys(values).forEach(function (i) {
if (typeof values[i] === "object") {
iterateParent = parent.slice();
iterateParent.push(i);
iterateValues(values[i], iterateParent, form, Array.isArray(values[i]));
} else {
form.append(getInput(i, values[i], parent, isArray));
}
});
};
var getInput = function (name, value, parent, array) {
var parentString;
if (parent.length > 0) {
parentString = parent[0];
var i;
for (i = 1; i < parent.length; i += 1) {
parentString += "[" + parent[i] + "]";
}
if (array) {
name = parentString + "[" + name + "]";
} else {
name = parentString + "[" + name + "]";
}
}
return $("<input>").attr("type", "hidden")
.attr("name", name)
.attr("value", value);
};
//----------------------------------------
// NOW THE SYNOPSIS
//----------------------------------------
var generatedForm = getForm(url, parameters);
$('body').append(generatedForm);
generatedForm.submit();
generatedForm.remove();
}
다음은 사용 방법의 예입니다.html 코드:
<button id="testButton">Button</button>
<script>
$(document).ready(function () {
$("#testButton").click(function () {
postForm({
csrf_token: "abcd",
rows: [
{
user_id: 1,
permission_group_id: 1
},
{
user_id: 1,
permission_group_id: 2
}
],
object: {
apple: {
color: "red",
age: "23 days",
types: [
"golden",
"opal",
]
}
},
the_null: null, // this will be dropped, like non-checked checkboxes are dropped
});
});
});
</script>
테스트 버튼을 클릭하면 폼이 투고되고 POST에 다음 값이 표시됩니다.
array(3) {
["csrf_token"] => string(4) "abcd"
["rows"] => array(2) {
[0] => array(2) {
["user_id"] => string(1) "1"
["permission_group_id"] => string(1) "1"
}
[1] => array(2) {
["user_id"] => string(1) "1"
["permission_group_id"] => string(1) "2"
}
}
["object"] => array(1) {
["apple"] => array(3) {
["color"] => string(3) "red"
["age"] => string(7) "23 days"
["types"] => array(2) {
[0] => string(6) "golden"
[1] => string(4) "opal"
}
}
}
}
주의: 현재 페이지가 아닌 다른 URL에 폼을 게시하려면 postForm 함수의 두 번째 인수로 URL을 지정할 수 있습니다.
예를 들어 (예시를 재사용하기 위해) 다음을 수행합니다.
postForm({'q':'a'}, 'http://example.com/');
이게 도움이 됐으면 좋겠다.
참고 2: 리다이렉트 플러그인에서 코드를 가져왔습니다.기본적으로 내 필요에 맞게 단순화한 것입니다.
jQuery의 트리거 메서드를 사용하여 버튼을 누르는 것처럼 폼을 전송할 수 있습니다.
$('form').trigger('submit')
브라우저에 제출됩니다.
해라
function post_to_url(url, obj) {
let id=`form_${+new Date()}`;
document.body.innerHTML+=`
<form id="${id}" action="${url}" method="POST">
${Object.keys(obj).map(k=>`
<input type="hidden" name="${k}" value="${obj[k]}">
`)}
</form>`
this[id].submit();
}
// TEST - in second param object can have more keys
function jump() { post_to_url('https://example.com/', {'q':'a'}); }
Open chrome>networks and push button:
<button onclick="jump()">Send POST</button>
언급URL : https://stackoverflow.com/questions/133925/javascript-post-request-like-a-form-submit
'programing' 카테고리의 다른 글
PHP 어레이의 예에서는 왜 말미에 쉼표가 남습니까? (0) | 2023.01.17 |
---|---|
Composer 실행 시 xdebug 사용 안 함 (0) | 2023.01.17 |
Vuex 스토어/내비게이션 가드가 처음 작동하지 않음 (0) | 2023.01.17 |
외부 키 제약 조건:업데이트 시 및 삭제 시 사용 시기 (0) | 2022.11.23 |
페이지 응답성을 높이려면 이벤트 핸들러를 '수동'으로 표시하십시오. (0) | 2022.11.23 |