简体   繁体   中英

How to pass form data using POST method and JS submit()?

How to pass form data using POST method and JS submit() ?

I would like not to use AJAX.

I can achieve that by using JS and GET method, but my goal now is to use JS (probably with submit() ) and POST method.

Please give a simple working example.

Thank you!

Edited: Sorry, I will be more specific. Here is a simple code I have:

<form name=\"myform\" action=\"\">
  Search: <input type='text' name='query' />
  <a href=\"javascript: submitform()\">Search</a>
</form>

 <script type=\"text/javascript\">
 function submitform() {   document.myform.submit(); }
 </script>

When I insert "word" into the input field and press Search, the URL becomes "../index.php?query=word" and that means that form data is passed like GET method.

And my goal is to remove any form data from URL and pass it like with POST method.

Edited: ohh.. I just added method=post and no form data in the URL anymore :)

Just have a form and submit it.

form = document.forms[0] //assuming only form.
form.submit();

EDIT: OP has clarified question

Specify a method attribute on your form.

<form name="myform" action="" method="POST">

It will cause the form to be submitted as a POST.

Set the form's method attribute to POST:

<form method="post">

And then submit the form via JavaScript using <formelement>.submit()

As mentioned already, you can use a form. I find it useful to have a function which creates a form on-the-fly and submits it - that way you don't need to clutter your markup with forms until they're needed by your JS.

function PostObjectToUri(uri, obj) {
    "use strict";

    var json, form, input;

    json = JSON.stringify(obj);

    form = document.createElement("form");
    form.method = "post";
    form.action = uri;
    input = document.createElement("input");
    input.setAttribute("name", "json");
    input.setAttribute("value", json);
    form.appendChild(input);
    document.body.appendChild(form);
    form.submit();
};

Obviously that example JSON-serializes an object into a string and sets it on a single input, but you could adapt it to do whatever you need.

EDIT : I'm not actually sure whether you even need to append to the DOM before submitting - can anyone clarify?

jQuery AJAX post is best way to do it. See below example code.

e.preventDefault();

$.ajax({
   type: 'post',
   url: 'data.php',
   data: $('form').serialize(),
   success: function(response) {
      $('#DisplayDiv').html(response);
   }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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