JQuery form submit adding request headers

前端 未结 1 1326
刺人心
刺人心 2021-01-20 08:56

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 si

相关标签:
1条回答
  • 2021-01-20 09:41

    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();
    });
    
    0 讨论(0)
提交回复
热议问题