I was reading the doc on how to set headers and there are apparently two ways one is with beforesend xhr and the other is just passing a object header with values. What's the difference between them?
beforeSend
$.ajax({
cache: false,
type: "GET",
url: "/",
beforeSend: function(xhr) {
xhr.setRequestHeader('x-access-token', token);
},
success: function(data) {
//Do something
},
error: function(data) {
//Do something
}
});
headers
$.ajax({
cache: false,
type: "GET",
url: "/",
headers: {
'x-access-token': token
},
success: function(data) {
//Do something
},
error: function(data) {
//Do something
}
});
The beforeSend() function use to set the custom headers and all, it is an Ajax event that triggers before an Ajax request is started. The false value returning in the beforeSend() function will cancel the Ajax request. Whatever the type of ajax request is there the beforeSend() function is always called.
The headers are additional key-value pairs send along with ajax request using the XMLHttpRequest object. An asynchronous HTTP request to the server by using The ajax() function and by including the header it describes to the server what kind of response it accept.
success() only gets called if your webserver responds with a 200 OK HTTP header - basically when everything is fine. However, . complete() will always get called no matter if the ajax call was successful or not - maybe it outputted errors and returned an error - . complete() will still get called.
Reviewing the docs, it looks like the only real difference (other than headers
being more concise and declarative) is that beforeSend
can override values from headers
. From the headers
section:
Values in the headers setting can also be overwritten from within the
beforeSend
function.
beforeSend
is also older than headers
, which were added in v1.5. (I assume beforeSend
was there prior to v1.5, since it has a note about how behavior changed as of v1.5).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With