如何提交带有标题的HTML表单

问题描述:

我想在发布请求期间提交包含标头的表单,这可能吗?我尝试使用下面的代码,但是无法发送带有已定义标头的请求.

I want to submit a form including a header during posting the request , is that possible ? I tried below code but I was unable to send the request with the defined header .


<html>
  <body>
  <script>
    var xhr = new XMLHttpRequest;
    xhr.setRequestHeader("Myheader" , "value")
  </script>
    <form action="https://example.com/myprofile/myedit" method="POST">
      <input type="hidden" name="firstname" value="Jacob&#32;" />
      <input type="hidden" name="email" value="jacob&#64;gmail&#46;com" />
      <input type="submit" value="Submit request" />
    </form>
  </body>
</html>

我想在发布请求期间提交包含标头的表单,这可能吗?

I want to submit a form including a header during posting the request , is that possible ?

否.

仅当您使用XMLHttpRequest或fetch进行请求时,才可以将自定义HTTP标头添加到请求中(因此,如果您使用表单提交来进行请求,则不能这样做).

You can only add custom HTTP headers to a request if you are using XMLHttpRequest or fetch to make the request (so you can't if you are using a form submission to make the request).

您可以使用 submit 事件来拦截表单提交,并使用XMLHttpRequest或fetch来发出请求………但是您也需要使用JS处理响应.

You could use the submit event to intercept the form submission and make the request with XMLHttpRequest or fetch instead … but then you'd need to handle the response with JS too.