JavaScript POST request like a form submit

Próbuję przekierować przeglądarkę na inną stronę. Gdybym chciał dostać wniosek, mógłbym powiedzieć

document.location.href = 'http://example.com/q=a';

Ale zasób, do którego próbuję uzyskać dostęp, nie odpowie poprawnie, chyba że użyję żądania POST. Jeśli nie były generowane dynamicznie, mógłbym użyć HTML

<form action="http://example.com/" method="POST">
  <input type="hidden" name="q" value="a">
</form>

Następnie chciałbym po prostu złożyć formularz z DOM.

Ale naprawdę chciałbym kod JavaScript, który pozwala mi powiedzieć

post_to_url('http://example.com/', {'q':'a'});

Jaka jest najlepsza przeglądarka wdrożenie?

Edit

Przepraszam, że nie wyraziłem się jasno. Potrzebuję rozwiązania, które zmieni lokalizację przeglądarki, tak jak wysłanie formularza. Jeśli jest to możliwe za pomocą XMLHttpRequest, nie jest to oczywiste. I to nie powinno być asynchroniczne, ani używać XML, więc Ajax nie jest odpowiedzią.
Author: Kamil Kiełczewski, 2008-09-25

30 answers

Dynamicznie Utwórz <input>s w formularzu i prześlij go

/**
 * 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 paramiters 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 wordy 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();
}

Przykład:

post('/contact/', {name: 'Johnny Bravo'});

EDIT: skoro to się tak bardzo upvoted, domyślam się, że ludzie będą kopiować-wklejać to często. Dodałem więc czek hasOwnProperty, aby naprawić wszelkie nieumyślne błędy.

 2224
Author: Rakesh Pai,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-05-03 20:47:35

Będzie to wersja wybranej odpowiedzi za pomocą 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();
}
 137
Author: Ryan Delucchi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-10-24 12:26:27

Prosta szybka i brudna implementacja @Aaron odpowiedz:

document.body.innerHTML += '<form id="dynForm" action="http://example.com/" method="post"><input type="hidden" name="q" value="a"></form>';
document.getElementById("dynForm").submit();

Oczywiście powinieneś raczej używać frameworka JavaScript, takiego jak Prototype lub jQuery ...

 75
Author: Alexandre Victoor,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-03-10 17:12:33

Użycie funkcji createElement dostarczonej w tej odpowiedzi , która jest niezbędna ze względu na ie z atrybutem name na elementach utworzonych normalnie z 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);
}
 55
Author: Jonny Buchanan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 10:31:38

Odpowiedź Rakesh Pai {[5] } jest niesamowita, ale jest problem, który pojawia się u mnie (w Safari), gdy próbuję opublikować formularz z polem o nazwie submit. Na przykład post_to_url("http://google.com/",{ submit: "submit" } );. Poprawiłem nieco funkcję, aby ominąć tę zmienną kolizję Kosmiczną.

    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!
 39
Author: Kendall Hopkins,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-01-16 21:54:58

Nie. Nie możesz mieć żądania JavaScript post, takiego jak wyślij formularz.

Możesz mieć formularz w HTML, a następnie przesłać go za pomocą JavaScript. (jak wyjaśniłem wielokrotnie na tej stronie).

Możesz utworzyć HTML samodzielnie, nie potrzebujesz JavaScript, aby napisać HTML. To byłoby głupie, gdyby ludzie to zasugerowali.

<form id="ninja" action="http://example.com/" method="POST">
  <input id="donaldduck" type="hidden" name="q" value="a">
</form>

Twoja funkcja po prostu skonfiguruje formularz tak, jak chcesz.

function postToURL(a,b,c){
   document.getElementById("ninja").action     = a;
   document.getElementById("donaldduck").name  = b;
   document.getElementById("donaldduck").value = c;
   document.getElementById("ninja").submit();
}

Następnie, użyj go jak.

postToURL("http://example.com/","q","a");

Ale ja bym po prostu pominął funkcja i po prostu zrobić.

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

Wreszcie decyzja o stylu trafia do pliku ccs.

#ninja{ 
  display:none;
}

Osobiście uważam, że formularze powinny być adresowane po imieniu, ale to nie jest teraz ważne.

 32
Author: gaby de wilde,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-03-07 17:34:29

Jeśli masz zainstalowany Prototype , możesz dokręcić kod, aby wygenerować i przesłać Ukryty formularz w następujący sposób:

 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();
 27
Author: Head,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-10-08 06:09:26

To jest odpowiedź rakesha, ale z obsługą tablic (co jest dość powszechne w formularzach):

Zwykły 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();
}
A oto wersja jquery: (trochę inny kod, ale sprowadza się do tego samego)
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(); 
}
 26
Author: kritzikratzi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-03-22 01:41:05

Jednym z rozwiązań jest wygenerowanie formularza i przesłanie go. Jedna implementacja to

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

Więc mogę zaimplementować bookmarklet skracający adres URL za pomocą prostego

javascript:post_to_url('http://is.gd/create.php', {'URL': location.href});
 18
Author: Joseph Holsten,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-09-25 16:05:21

Cóż, szkoda, że nie przeczytałem wszystkich innych postów, więc nie straciłem czasu na tworzenie tego na podstawie odpowiedzi Rakesh Pai. Oto rozwiązanie rekurencyjne, które działa z tablicami i obiektami. Brak zależności od jQuery.

Dodano segment do obsługi przypadków, w których cały formularz powinien być przesłany jak tablica. (tj. gdzie nie ma obiektu wrappera wokół listy elementów)

/**
 * 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();
};
 17
Author: emragins,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-20 11:21:24

Najprostszym sposobem jest użycie Ajax POST Request:

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

Gdzie:

  • dane są obiektem
  • dataType to dane oczekiwane przez serwer (xml, json, script, text, html)
  • url to adres Twojego serwera RESt lub dowolnej funkcji po stronie serwera, która akceptuje HTTP-POST.

Następnie w Success handler przekieruj przeglądarkę z czymś w rodzaju window.miejsce.

 14
Author: JLavoie,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-19 18:57:24

Trzy opcje tutaj.

  1. Standardowa odpowiedź JavaScript: użyj frameworka! Większość frameworków Ajax będzie miała prosty sposób na napisanie posta XMLHTTPRequest.

  2. Zrób żądanie XMLHTTPRequest samodzielnie, przekazując post do metody open zamiast get. (Więcej informacji w używanie metody POST w XMLHTTPRequest (Ajax).)

  3. Poprzez JavaScript, dynamicznie twórz formularz, Dodaj akcję, Dodaj swoje dane wejściowe i prześlij to.

 13
Author: Alan Storm,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-03-10 17:08:32

Ja bym poszedł trasą Ajax jak inni sugerowali z czymś takim:

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");
 13
Author: Katy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-08-21 09:21:43

Oto Jak to napisałem używając jQuery. Testowane w przeglądarce Firefox i 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();
}
 12
Author: beauburrier,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-06 09:01:32

Biblioteka Prototype zawiera obiekt Hashtable, z ".toquerystring ()" metoda, która pozwala na łatwe przekształcenie obiektu/struktury JavaScript w ciąg zapytania. Ponieważ post wymaga, aby "ciało" żądania było sformatowanym ciągiem zapytania, pozwala to na prawidłowe działanie żądania Ajax jako post. Oto przykład użycia prototypu:

$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();
};
 7
Author: Adam Ness,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-03-10 17:10:24

To działa idealnie w moim przypadku:

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

Można go używać w funkcji:

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

Za pomocą tego można umieścić wszystkie wartości wejść.

 5
Author: Chintan Thummar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-06 09:06:51

Moje rozwiązanie zakoduje głęboko zagnieżdżone obiekty, w przeciwieństwie do obecnie akceptowanego rozwiązania przez @ RakeshPai.

Używa biblioteki ' qs ' npm i jej funkcji stringify do konwersji zagnieżdżonych obiektów na parametry.

Ten kod działa dobrze z zapleczem Rails, chociaż powinieneś być w stanie zmodyfikować go tak, aby działał z każdym backendem, którego potrzebujesz, modyfikując opcje przekazane do stringify. Rails wymaga ustawienia arrayFormat na "nawiasy".

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

Przykład:

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

Produkuje te parametry szyn:

{"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"]}]}
 5
Author: cmrichards,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-31 22:03:28

Yet another recursive solution, since some of other seems to be broken (I didn ' t tested all of them). To zależy od lodash 3.x i ES6 (jQuery nie jest wymagane):

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();
}
 4
Author: mpen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-11 21:22:51

FormObject jest opcją. Ale FormObject nie jest teraz obsługiwany przez większość przeglądarek.

 2
Author: lingceng,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-21 09:07:14

To jest jak opcja Alana 2 (powyżej). Jak utworzyć instancję httpobj jest pozostawiony jako ćwiczenie.

httpobj.open("POST", url, true);
httpobj.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');
httpobj.onreadystatechange=handler;
httpobj.send(post);
 1
Author: Robert Van Hoose,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-09-25 15:40:48

Jest to oparte na kodzie beauSD używającym jQuery. Jest ulepszony tak, że działa rekurencyjnie na obiektach.

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();
}
 1
Author: bobef,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-05-27 13:19:34

Możesz dynamicznie dodać formularz za pomocą DHTML, a następnie przesłać.

 1
Author: AnthonyWJones,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-03-10 17:05:18

Możesz użyć biblioteki takiej jak jQuery i jej $.metoda post .

 1
Author: Bill Turner,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-03-10 17:05:56

Używam dokumentu.tworzy Javę i zapętla ją, aby pobrać wszystkie elementy w formularzu, a następnie wysłać przez xhttp. Tak więc jest to moje rozwiązanie dla Javascript / ajax submit (z całym html dołączonym jako przykład):

          <!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>
 1
Author: drtechno,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-01-20 01:41:16

Metoda, której używam do automatycznego wysyłania i kierowania użytkownika na inną stronę, polega na napisaniu ukrytego formularza, a następnie automatycznym przesłaniu go. Upewnij się, że ukryta forma nie zajmuje absolutnie żadnego miejsca na stronie internetowej. Kod byłby taki:

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

Aplikacja auto submit

Aplikacja auto submit kierowałaby wartości formularzy, które Użytkownik automatycznie wstawia na drugiej stronie z powrotem do tej strony. Taka aplikacja byłaby jak to:

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();
}
 0
Author: rauprog,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-25 08:37:10

Oto Jak to robię.

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();
    }
 0
Author: nikksan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-06 23:14:25

JQuery plugin for redirect with POST or GET:

Https://github.com/mgalante/jquery.redirect/blob/master/jquery.redirect.js

Aby przetestować, załącz powyższe .plik js lub skopiuj / wklej klasę do kodu, a następnie użyj kodu tutaj, zastępując "args" nazwami zmiennych, a "values"wartościami odpowiednich zmiennych:

$.redirect('demo.php', {'arg1': 'value1', 'arg2': 'value2'});
 0
Author: OG Sean,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-09 00:22:21

Żadne z powyższych rozwiązań nie obsługiwało głębokich zagnieżdżonych param tylko jQuery, oto moje rozwiązanie.

Jeśli używasz jQuery i musisz obsługiwać głęboko zagnieżdżone parametry, możesz użyć tej funkcji poniżej:

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

Oto przykład, jak z niego korzystać. Kod 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>

I jeśli klikniesz przycisk test, zamieści formularz i otrzymasz następujące wartości w poście:

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"
      }
    }
  }
}

Uwaga: Jeśli chcesz zamieścić formularz na innym adresie url niż bieżąca strona, możesz podać adres url jako drugi argument funkcji postForm.

Tak na przykład (aby ponownie wykorzystać twój przykład):

postForm({'q':'a'}, 'http://example.com/');
Mam nadzieję, że to pomoże.

Note2: kod został pobrany z wtyczki redirect . W zasadzie to uprościłem na moje potrzeby.

 0
Author: ling,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-12-10 09:32:55

Możesz użyć metody jQuery trigger do przesłania formularza, tak jak naciskasz przycisk, Tak,

$('form').trigger('submit')

Zostanie wysłana w przeglądarce.

 0
Author: Canaan Etai,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-01-08 14:01:06

Try

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>
 0
Author: Kamil Kiełczewski,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-06-15 19:59:30