How to set a Header field on POST a form?

前端 未结 8 1843
情书的邮戳
情书的邮戳 2020-11-27 04:08

How can I set a custom field in POST header on submit a form?

相关标签:
8条回答
  • 2020-11-27 05:00

    To add into every ajax request, I have answered it here: https://stackoverflow.com/a/58964440/1909708


    To add into particular ajax requests, this' how I implemented:

    var token_value = $("meta[name='_csrf']").attr("content");
    var token_header = $("meta[name='_csrf_header']").attr("content");
    $.ajax("some-endpoint.do", {
     method: "POST",
     beforeSend: function(xhr) {
      xhr.setRequestHeader(token_header, token_value);
     },
     data: {form_field: $("#form_field").val()},
     success: doSomethingFunction,
     dataType: "json"
    });
    

    You must add the meta elements in the JSP, e.g.

    <html>
    <head>        
        <!-- default header name is X-CSRF-TOKEN -->
        <meta name="_csrf_header" content="${_csrf.headerName}"/>
        <meta name="_csrf" content="${_csrf.token}"/>
    

    To add to a form submission (synchronous) request, I have answered it here: https://stackoverflow.com/a/58965526/1909708

    0 讨论(0)
  • 2020-11-27 05:04

    You could use $.ajax to avoid the natural behaviour of <form method="POST">. You could, for example, add an event to the submission button and treat the POST request as AJAX.

    0 讨论(0)
提交回复
热议问题