Darkrum
Darkrum

Reputation: 1383

jquery ajax difference between header and beforesend

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
    }
});

Upvotes: 7

Views: 2126

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074979

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).

Upvotes: 8

Related Questions