Does anyone know how to add or create a custom HTTP header using JavaScript or jQuery?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- Carriage Return (ASCII chr 13) is missing from tex
- How to fix IE ClearType + jQuery opacity problem i
- void before promise syntax
Assuming JQuery ajax, you can add custom headers like -
Assuming that you mean "When using ajax" and "An HTTP Request header", then use the
headers
property in the object you pass toajax()
— http://api.jquery.com/jQuery.ajax/
Here's an example using XHR2:
Hope that helps.
If you create your object, you can use the setRequestHeader function to assign a name, and a value before you send the request.
You should avoid the usage of
$.ajaxSetup()
as described in the docs. Use the following instead:There are several solutions depending on what you need...
If you want to add a custom header (or set of headers) to an individual request then just add the
headers
property:If you want to add a default header (or set of headers) to every request then use
$.ajaxSetup()
:If you want to add a header (or set of headers) to every request then use the
beforeSend
hook with$.ajaxSetup()
:Edit (more info): One thing to be aware of is that with
ajaxSetup
you can only define one set of default headers and you can only define onebeforeSend
. If you callajaxSetup
multiple times, only the last set of headers will be sent and only the last before-send callback will execute.You can also do this without using jQuery. Override XMLHttpRequest's send method and add the header there: