简体   繁体   English

JavaScript post request like a form submit

[英]JavaScript post request like a form submit

I'm trying to direct a browser to a different page.我正在尝试将浏览器定向到不同的页面。 If I wanted a GET request, I might say如果我想要一个 GET 请求,我可能会说

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

But the resource I'm trying to access won't respond properly unless I use a POST request.但是除非我使用 POST 请求,否则我尝试访问的资源不会正确响应。 If this were not dynamically generated, I might use the HTML如果这不是动态生成的,我可能会使用 HTML

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

Then I would just submit the form from the DOM.然后我会从 DOM 提交表单。

But really I would like JavaScript code that allows me to say但我真的想要 JavaScript 代码让我说

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

What's the best cross browser implementation?最好的跨浏览器实现是什么?

Edit编辑

I'm sorry I was not clear.对不起,我不清楚。 I need a solution that changes the location of the browser, just like submitting a form.我需要一个改变浏览器位置的解决方案,就像提交表单一样。 If this is possible with XMLHttpRequest , it is not obvious.如果这对XMLHttpRequest是可能的,那么它并不明显。 And this should not be asynchronous, nor use XML, so Ajax is not the answer.而且这个应该不是异步的,也不是用XML,所以Ajax不是答案。

Dynamically create <input> s in a form and submit it在表单中动态创建<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();
}

Example:例子:

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

EDIT : Since this has gotten upvoted so much, I'm guessing people will be copy-pasting this a lot.编辑:由于这已经得到了如此多的支持,我猜人们会大量复制粘贴它。 So I added the hasOwnProperty check to fix any inadvertent bugs.所以我添加了hasOwnProperty检查来修复任何无意中的错误。

This would be a version of the selected answer using jQuery .这将是使用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();
}

A simple quick-and-dirty implementation of @Aaron answer: @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();

Of course, you should rather use a JavaScript framework such as Prototype or jQuery ...当然,您应该使用 JavaScript 框架,例如PrototypejQuery ...

Using the createElement function provided in this answer , which is necessary due to IE's brokenness with the name attribute on elements created normally with document.createElement :使用此答案中提供的createElement函数,这是必要的,因为IE 破坏了使用document.createElement正常创建的元素的 name 属性

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's answer is amazing, but there is an issue that occurs for me (in Safari ) when I try to post a form with a field called submit . Rakesh Pai 的回答很棒,但是当我尝试发布一个带有名为submit的字段的表单时,我(在Safari 中)出现了一个问题。 For example, post_to_url("http://google.com/",{ submit: "submit" } );例如, post_to_url("http://google.com/",{ submit: "submit" } ); . . I have patched the function slightly to walk around this variable space collision.我已经稍微修补了这个函数来绕过这个可变空间碰撞。

    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!

No. You can't have the JavaScript post request like a form submit.不可以。您不能像提交表单那样使用 JavaScript 发布请求。

What you can have is a form in HTML, then submit it with the JavaScript.您可以拥有一个 HTML 格式的表单,然后使用 JavaScript 提交它。 (as explained many times on this page). (正如本页多次解释的那样)。

You can create the HTML yourself, you don't need JavaScript to write the HTML.您可以自己创建 HTML,不需要 JavaScript 来编写 HTML。 That would be silly if people suggested that.如果有人这么建议,那将是愚蠢的。

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

Your function would just configure the form 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();
}

Then, use it like.然后,像这样使用它。

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

But I would just leave out the function and just do.但我会忽略这个功能而只是去做。

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

Finally, the style decision goes in the ccs file.最后,样式决定在 ccs 文件中。

#ninja{ 
  display:none;
}

Personally I think forms should be addressed by name but that is not important right now.我个人认为表格应该按名称寻址,但现在这并不重要。

this is the answer of rakesh, but with support for arrays (which is quite common in forms):这是 rakesh 的答案,但支持数组(这在表单中很常见):

plain javascript:普通的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();
}

oh, and here's the jquery version: (slightly different code, but boils down to the same thing)哦,这是 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(); 
}

If you have Prototype installed, you can tighten up the code to generate and submit the hidden form like this:如果您安装了Prototype ,您可以收紧代码以生成和提交隐藏表单,如下所示:

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

One solution is to generate the form and submit it.一种解决方案是生成表单并提交。 One implementation is一种实现是

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

So I can implement a URL shortening bookmarklet with a simple所以我可以用一个简单的实现一个 URL 缩短书签

javascript:post_to_url('http://is.gd/create.php', {'URL': location.href});

Well, wish I had read all the other posts so I didn't lose time creating this from Rakesh Pai's answer.好吧,希望我已经阅读了所有其他帖子,这样我就不会浪费时间从 Rakesh Pai 的回答中创建这个。 Here's a recursive solution that works with arrays and objects.这是一个适用于数组和对象的递归解决方案。 No dependency on jQuery.不依赖于 jQuery。

Added a segment to handle cases where the entire form should be submitted like an array.添加了一个段来处理整个表单应该像数组一样提交的情况。 (ie. where there's no wrapper object around a list of items) (即,在项目列表周围没有包装对象的地方)

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

I'd go down the Ajax route as others suggested with something like:我会像其他人建议的那样沿着 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");

Three options here.这里有三个选项。

  1. Standard JavaScript answer: Use a framework!标准 JavaScript 答案:使用框架! Most Ajax frameworks will have abstracted you an easy way to make an XMLHTTPRequest POST.大多数 Ajax 框架都为您提供了一种简单的方法来制作XMLHTTPRequest POST。

  2. Make the XMLHTTPRequest request yourself, passing post into the open method instead of get.自己发出 XMLHTTPRequest 请求,将 post 传递到 open 方法而不是 get。 (More information in Using POST method in XMLHTTPRequest (Ajax) .) 在 XMLHTTPRequest (Ajax)使用 POST 方法中的更多信息。)

  3. Via JavaScript, dynamically create a form, add an action, add your inputs, and submit that.通过 JavaScript,动态创建表单、添加操作、添加输入并提交。

The easiest way is using Ajax Post Request:最简单的方法是使用 Ajax Post Request:

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

where:在哪里:

  • data is an object数据是一个对象
  • dataType is the data expected by the server (xml, json, script, text, html) dataType 是服务器期望的数据(xml、json、script、text、html)
  • url is the address of your RESt server or any function on the server side that accept the HTTP-POST. url 是您的 REST 服务器或接受 HTTP-POST 的服务器端的任何函数的地址。

Then in the success handler redirect the browser with something like window.location.然后在成功处理程序中使用类似 window.location 的内容重定向浏览器。

Here is how I wrote it using jQuery.这是我使用 jQuery 编写它的方式。 Tested in Firefox and Internet Explorer.在 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();
}

The Prototype library includes a Hashtable object, with a ".toQueryString()" method, which allows you to easily turn a JavaScript object/structure into a query-string style string. Prototype库包括一个带有“.toQueryString()”方法的 Hashtable 对象,它允许您轻松地将 JavaScript 对象/结构转换为查询字符串样式的字符串。 Since the post requires the "body" of the request to be a query-string formatted string, this allows your Ajax request to work properly as a post.由于帖子要求请求的“主体”是查询字符串格式的字符串,这允许您的 Ajax 请求作为帖子正常工作。 Here's an example using Prototype:下面是一个使用 Prototype 的例子:

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

This works perfectly in my case:这在我的情况下非常有效:

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

You can use it in function like:您可以在以下功能中使用它:

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

Using this you can post all the values of inputs.使用它,您可以发布所有输入值。

My solution will encode deeply nested objects, unlike the currently accepted solution by @RakeshPai.我的解决方案将对深度嵌套的对象进行编码,这与@RakeshPai 目前接受的解决方案不同。

It uses the 'qs' npm library and its stringify function to convert nested objects into parameters.它使用“qs”npm 库及其 stringify 函数将嵌套对象转换为参数。

This code works well with a Rails back-end, although you should be able to modify it to work with whatever backend you need by modifying the options passed to stringify.此代码适用于 Rails 后端,尽管您应该能够通过修改传递给 stringify 的选项来修改它以与您需要的任何后端一起使用。 Rails requires that arrayFormat be set to "brackets". 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();
}

Example:例子:

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

Produces these Rails parameters:产生这些 Rails 参数:

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

Yet another recursive solution, since some of others seem to be broken (I didn't test all of them).另一个递归解决方案,因为其他一些似乎已损坏(我没有测试所有这些)。 This one depends on lodash 3.x and ES6 (jQuery not required):这个依赖于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 动态添加表单,然后提交。

FormObject is an option. FormObject是一个选项。 But FormObject is not supported by most browsers now.但是现在大多数浏览器都不支持 FormObject。

您可以使用像 jQuery 这样的库及其$.post 方法

This is like Alan's option 2 (above).这就像 Alan 的选项 2(上图)。 How to instantiate the httpobj is left as an excercise.如何实例化 httpobj 留作练习。

httpobj.open("POST", url, true);
httpobj.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');
httpobj.onreadystatechange=handler;
httpobj.send(post);

I use the document.forms java and loop it to get all the elements in the form, then send via xhttp.我使用 document.forms java 并循环它以获取表单中的所有元素,然后通过 xhttp 发送。 So this is my solution for javascript / ajax submit (with all html included as an example):所以这是我的javascript/ajax提交解决方案(以所有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>

This is based on beauSD's code using jQuery.这是基于使用 jQuery 的 beauSD 代码。 It is improved so it works recursively on objects.它得到了改进,因此它可以递归地处理对象。

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

The accepted answer will reload the page like a native form submit.接受的答案将像本机表单提交一样重新加载页面。 This modified version, will submit through XHR:这个修改后的版本,将通过 XHR 提交:

function post(path, params) {
  const form = document.createElement('form');

  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);
    }
  }
  var button = form.ownerDocument.createElement('input');
  button.type = 'submit';
  form.appendChild(button);

  form.onsubmit = async function (e) {
    console.log('hi');

    e.preventDefault();
    const form = e.currentTarget;

    try {
      const formData = new FormData(form);
      const response = await fetch(path, {
        method: 'POST',
        body: formData,
      });

      console.log(response);
    } catch (error) {
      console.error(error);
    }
  };

  document.body.appendChild(form);
  button.click();
}

The method I use to post and direct a user automatically to another page is to just write a hidden form and then auto submit it.我用来发布和自动引导用户到另一个页面的方法是只写一个隐藏的表单,然后自动提交它。 Be assured that the hidden form takes absolutely no space on the web page.请放心,隐藏的表单在网页上绝对不占空间。 The code would be something like this:代码将是这样的:

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

Application of auto submit申请自动提交

An application of an auto submit would be directing form values that the user automatically put in on the other page back to that page.自动提交的应用程序会将用户自动放入另一个页面的表单值引导回该页面。 Such an application would be like this:这样的应用程序将是这样的:

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

Here is how I do it.这是我如何做到的。

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

jQuery plugin for redirect with POST or GET:用于使用 POST 或 GET 重定向的 jQuery 插件:

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

To test, include the above .js file or copy/paste the class into your code, then use the code here, replacing "args" with your variable names, and "values" with the values of those respective variables:要进行测试,请包含上面的 .js 文件或将类复制/粘贴到您的代码中,然后使用此处的代码,将“args”替换为您的变量名称,并将“values”替换为相应变量的值:

$.redirect('demo.php', {'arg1': 'value1', 'arg2': 'value2'});

You could use jQuery's trigger method to submit the form, just like you press a button, like so,你可以使用jQuery的trigger方法来提交表单,就像你按下按钮一样,像这样,

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

it will submit on the browser.它将在浏览器上提交。

None of the above solutions handled deep nested params with just jQuery, so here is my two cents solution.上述解决方案都没有仅使用 jQuery 处理深层嵌套参数,所以这是我的 2 美分解决方案。

If you're using jQuery and you need to handle deep nested parameters, you can use this function below:如果您使用 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();
    }

Here is an example of how to use it.这是一个如何使用它的示例。 The html code: 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>

And if you click the test button, it will post the form and you will get the following values in POST:如果您单击测试按钮,它将发布表单,您将在 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"
      }
    }
  }
}

Note: if you want to post the form to another url than the current page, you can specify the url as the second argument of the postForm function.注意:如果要将表单发布到当前页面以外的其他 url,可以将 url 指定为 postForm 函数的第二个参数。

So for instance (to re-use your example):例如(重新使用您的示例):

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

Hope this helps.希望这可以帮助。

Note2: the code was taken from the redirect plugin .注2:代码取自重定向插件 I basically just simplified it for my needs.我基本上只是根据我的需要简化了它。

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>

You could make an AJAX call (likely using a library such as using Prototype.js or JQuery). 您可以进行AJAX调用(可能使用诸如使用Prototype.js或JQuery之类的库)。 AJAX can handle both GET and POST options. AJAX可以处理GET和POST选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM