JQuery form submit adding request headers

2020-04-11 11:43发布

问题:

I want to ask is it possible to specify headers before calling $(myForm).submit(); I know you can specify in AJAX post request but is it possible before this simple form submit ?

回答1:

Yes you can. Requires some native JavaScript drudgery, this is how I did it:

<!DOCTYPE html>
<html>

  <body>
    <h1>Custom Header Injection 1</h1>
    <div id="header_demo">
      <form id="custom_form">
        <input type="hidden" name="name_1" value="${form.name_1}" />
        <button type="button" onclick="submitFormAndHeader()">Submit Form</button>
      </form>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
    <script>
      function submitFormAndHeader() {
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
          if (this.readyState == 4 && this.status == 200) {
            document.getElementById("demo").innerHTML =
              this.responseText;
          }
        };
        xhttp.open("POST", "/v1/target-endpoint.do", true);
        xhttp.setRequestHeader("custom_header", "test value of custom header");
        xhttp.send($("#custom_form").serialize());
      }

    </script>
  </body>

</html>

Added a function submitFormAndHeader which creates an XMLHttpRequest object that adds the required headers and submits a HTML DOM form via HTTP POST.


Alternatively, you can use Jquery submit handler and invoke the submitFormAndHeader() function created above:

$( "#custom_form" ).on( "submit", function( event ) {
  event.preventDefault();
  submitFormAndHeader();
});