Custom Headers in AJAX POST Requests with jQuery
In AJAX POST requests initiated with jQuery, it is possible to include custom headers. However, the mechanism for adding headers differs from the typical approach.
When you specify headers as shown in the example:
$.ajax({ type: 'POST', url: url, headers: { "My-First-Header":"first value", "My-Second-Header":"second value" } }).done(function(data) { alert(data); });
Understandably, you would expect the headers to be sent as:
My-First-Header: first value My-Second-Header: second value
However, browser security measures prevent sending the custom header values directly in the initial request. Instead, they are placed in the Access-Control-Request-Headers header. This is a security mechanism known as the preflighted request.
To allow the subsequent request to include the actual header values, the server must configure the necessary CORS (Cross-Origin Resource Sharing) headers.
A solution to this is sending the headers in a different way, as shown in the given sample code:
$.ajax({ type: "POST", beforeSend: function(request) { request.setRequestHeader("Authority", authorizationToken); }, url: "entities", data: "json=" + escape(JSON.stringify(createRequestObject)), processData: false, success: function(msg) { $("#results").append("The result =" + StringifyPretty(msg)); } });
This approach actually sets the request header values directly, bypassing the Access-Control-Request-Headers placement. It provides a way to send custom headers with the initial request without requiring server configuration.
The above is the detailed content of How to Send Custom Headers in AJAX POST Requests with jQuery?. For more information, please follow other related articles on the PHP Chinese website!