양식 제출과 같은 자바스크립트 게시물 요청

브라우저를 다른 페이지로 리디렉션하려고 합니다. 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]1로 이것이 가능하다면 분명하지 않습니다. 그리고 이것은 비동기식이어서는 안되며 XML을 사용해서는 안되므로 Ajax는 정답이 아닙니다.

질문에 대한 의견 (1)
해결책

It # 만들기 '의 형태로 제출됩니다 input&gt 무중단으로 <;

"'js /*

  • sends 지정된 url 에 요청을 양식에서. 이렇게 하면 변경하십시오 창 위치.
  • 경로 문자열을 @param {} 경로를 전송하십시오 게시물로의 요청
  • @param {객체} 이 파라미터스 uirl 추가할 params
  • [방법 = 게시물로의]} {문자열이어야 @param 양식에 사용 방법 */

함수은 게시물로의 (# 39, & # 39 post& 경로를 params 방법 =;;) {

이 코드를 사용하지 않는 것으로 // 미삭 라리브러리. 말 많은 덜 사용하는 경우 // 이 만들 수 있습니다. const 양식을 도쿠망스크리틸망 (& # 39, form& # 39;), = 포르메이휴메트로트 = 방법. 포m.악타이온 = 경로.

대한 (const 키를 params) { if (파라 s.하스운프로페티 (키) { const 이든필드 도쿠망스크리틸망 (& # 39, input& # 39;), =

39, & # 39 hidden& 이든필드스티페 =;;

hiddenField.name = 키. 이든필드스발루 = params [핵심];

포르마리아펜드차일드 (이든필드); } }

도쿠망.보디지아펜드차일드 (양식). 포르마리서브미스 (); }

"'

예:

"'js 사후 (& # 39, /contact/& # 39, {이름: # 39, & # 39 존이니 Bravo&,}). "'

  • 편집할지 *: 이 때문에 업보테드 된 이후, 이 사람들이 너무 많이 복사 붙여 넣기 I& # 39 m 추측 된다. 그래서 '벅스' 부주의한 해결하십시오 추가했어야 해스운프로페티 확인합니다.
해설 (17)

이 약간만이라도 선택된 버전을 사용하는 오토메이티드 [jQuery] [1].


// Post to the provided URL with the specified parameters.
function post(path, parameters) {
    var form = $('');

    form.attr("method", "post");
    form.attr("action", path);

    $.each(parameters, function(key, value) {
        var field = $('<input>
해설 (4)

간단한 빠른 및 더러운 구현 @Aaron 대답:

document.body.innerHTML += '<input type="hidden" name="q" value="a">';
document.getElementById("dynForm").submit();

물론, 자바스크립트 프레임워크 등 사용하지 않고 합니다 프로토타입 또는 jQuery.

해설 (2)

[이 오토메이티드] [1] 에서 제공하는 ',' 기능을 사용하여 크리틸망 인해 필요한 [IE& # 39 의 부서짐 이름 속성과] [2] 일반적으로 도쿠망스크리틸망 함께 만든 '요소':

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

[1]: https://stackoverflow.com/questions/118693/how-do-you-dynamically-create-a-radio-button-in-javascript-that-works-in-all-br # 120372 [2]: 이아스파스 http://msdn.microsoft.com/en-us/library/ms534184 (VS.85)

해설 (3)

[# 39 의 케쉬 Pai& 오토메이티드] [1] 은 놀랍슴돠 발생하는 문제가 있었지만, 나를 위해 (in [사파리] [2]) '라고 할 때 나는 양식을 게시물로의 필드와 제출됩니다'. 예를 들어, {제출: http://google.com/ &quot 'post_to_url ("; &quot 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!

[1]: # 133997 https://stackoverflow.com/questions/133925/javascript-post-request-like-a-form-submit/133997 [2]: http://en.wikipedia.org/wiki/Safari_% 28web_browser% 29

해설 (1)

아니야 넌 # 39, 양식 등 제출됩니다 JavaScript 게시물로의 요청임을 can& 없다.

어떤 it 의 JavaScript 는 HTML 형식으로 제출 후 할 수 있습니다. (이 페이지의 설명한 여러 번).

39, HTML 교도관님도요 전날에약혼자에게 don& JavaScript 를 생성할 수 있는 HTML 기록하십시오 필요한 건 아니다. 어리석은 사람이 될 경우 것을 제안했다.


  <input id="donaldduck" type="hidden" name="q" value="a">

이 함수는 그냥 양식을 구성하시겠습니까 the way you want it.

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

하지만 난 그냥 남겨두십시오 아웃해야 기능, just do.

document.getElementById('donaldduck').value = "a";
document.getElementById("ninja").submit();

마지막으로, 스타일 진단트리 댁이라면 config. ccs 절실해졌습니다.

#ninja{ 
  display:none;
}

개인적으로 양식 의해 수행되어야 한다는 그런 건 중요하지 않아 제말들어요 이름만 생쥐라.

해설 (0)

프로토타입 가 설치되어 있는 경우, 다음과 같은 코드를 수정하여 조이십시오 백업하도록 제출됩니다 숨겨진 양식을 생성할 수 있습니다.

 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();
해설 (0)

하지만 이것은 답을 케쉬 지원할 수 있는 시스템 (원하는거요 매우 일반적인 forms):

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

아, 그리고 here& # 39 의 버전을 포함한다. (하지만, 결국 약간 다른 코드를 down to the 같은 것입니다.)

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

하나의 해법은 양식을 발령합니다 제출됩니다 거잖나. 한 구현은

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

음, 그래서 다른 모든 사람이 읽을 수 있었으면 좋겠다, t, s # 39 에서 제작 시간을 손실됩니다 케쉬 Pai& didn& # 39 이 답이다. # 39 의 here& 재귀 솔루션을 사용할 수 있는 시스템 및 객체에는. Jquery 의존하지 않음.

전체 형 같은 경우를 처리할 수 있는 것이라고 세그먼트마다 어레이에서는 제출해야 합니다. (예: # 39, 래퍼 객체에는 there& 항목의 목록을 주위에 있는 게 전혀 없다)

/**
 * 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();
};
해설 (3)

내가 어떻게 작성했습니까 슬라이드에서는 사용하여 해당 포함한다. Firefox 에서 테스트되었습니다 및 Internet&amp, nbsp, 탐험가이다.

function postToUrl(url, params, newWindow) {
    var 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();
}
해설 (4)

39 i& Ajax 로 다운 라우트를 제안됩니다 다음과 같은 항목을 통해 다른; d

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");
해설 (2)

여기서 세 가지 옵션.

  1. 표준 JavaScript 대답: 사용 프레임워크입니다! 가장 쉽게 할 수 있도록 아약스 프레임워크와도 추상화 너희에의 ui_policytable_java_spe_policy 스믈하트프리퀘스트 POST.

  2. 요청을 할 교도관님도요, 스믈하트프리퀘스트 를 열기 방법 대신 반군지역 게시물로의 프레젠테이션이든. (더 많은 정보를 게시물로의 메서드를 사용하여 스믈하트프리퀘스트 (아약스) .)

  3. Javascript 를 통해 동적으로 만들 수 있는 형태로, 추가 작업을 추가할 투입물, 제출됩니다 iqn.

해설 (2)

가장 쉬운 방법은 Ajax 를 사용하여 http://competitivehelp

$.ajax({
    type: "POST",
    url: 'http://www.myrestserver.com/api',
    data: data,
    success: success,
    dataType: dataType
    });

여기서:

  • 데이터 객체가
  • 데이터 형식 () 은 데이터 필요한 서버 (xml, json, 스크립트, 텍스트, html)
  • 주소 url 은 서버 측에서 어떤 함수를 통해 미삭 서버또는 받아들이는 http post.

그럼 성공 처리기에서 리디렉션하십시오 브라우저로 빈다우드로카티언스 같은 일이

해설 (3)

프로토타입 는 해스터블 객체를 라이브러리란 포함되어 있는 &quot &quot 네스토크리스트링 ();; 쉽게 바꿀 수 있는 방법을 JavaScript 객체로 / 구조 붙여넣습니다 쿼리 문자열 스타일입니까 구체화하십시오. 이후, body&quot 게시물로의 &quot 필요합니다. 이 사용하면 Ajax 요청을 포맷되었을 문자열이어야 쿼리 문자열 요청을 할 수 있다. # 39 의 제대로 작동하도록 게시물로의 here& 사용한 예는 시제품:

$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();
};
해설 (1)

이 작품은 완벽하게 내 경우:

document.getElementById("form1").submit();

이 같은 기능을 사용할 수 있습니다.

function formSubmit() {
     document.getElementById("frmUserList").submit();
} 

이 모든 투입물 값을 사용하여 게시할 수 있습니다.

해설 (0)

내 솔루션은 현재 깊이 네스트된 객체에는 인코딩합니다 달리 수락됨 솔루션을 출시해 @RakeshPai.

39, & # 39 qs& 사용합니다. 고궁박물원 라이브러리 및 해당 스트린그리피 변환할지 함수은 네스트된 오브젝트로 매개변수입니다.

이 코드는 제대로 작동하도록 수정할 수 있어야 할 수 있지만, 백 수신기마다 레일 있는모든 백 옵션 수정하여 스트린그리피 전달된 합니다. 레일 라이포르마 brackets&quot &quot 설정되어야 합니다;;).

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"]}]}
해설 (0)
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();
}
해설 (0)

[포르모비치] (https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects) 는 옵션입니다. 하지만 이제 포르모비치 대부분의 브라우저에서 지원되지 않습니다.

해설 (0)

DHTML을 사용하여 양식을 동적으로 추가한 다음 제출할 수 있습니다.

해설 (0)