javascript - jQuery ajax beforeSend shadows the `$.ajaxSetup` one, How to cascade it? -


i'm using django-rest-framework.

and have add x-csrftoken header before every jquery ajax send.

ref: https://docs.djangoproject.com/en/1.8/ref/csrf/#ajax

jquery.ajaxsetup({     beforesend: function(xhr, settings) {         if (!csrfsafemethod(settings.type) && !this.crossdomain) {             xhr.setrequestheader("x-csrftoken", cookies.get('csrftoken'));         }     } }); 

so, until make ajax call beforesend setting given:

jquery.ajax({     url: '...',     data: { ... },     beforesend: function(xhr, settings) {         // function shadows ajaxsetup one.     } }); 

so, there efficient way cascade beforesend processors on jquery.ajaxsetup call?

in fact, in jquery document of jquery event, setting beforesend $.ajax call or $.ajaxsetup called local event, in current case, using $(document).ajaxsend() called global event more suitable.


final solution

in case if want add multiple global event processor on ajax send, not set on $.ajaxsetup.

use ajaxsend event instead!

http://api.jquery.com/ajaxsend/

so code may like:

function csrfsafemethod(method) {     // these http methods not require csrf protection     return (/^(get|head|options|trace)$/.test(method)); } $(document).ajaxsend(function(event, xhr, settings) {     if (!csrfsafemethod(settings.type) && !settings.crossdomain) {         xhr.setrequestheader("x-csrftoken", cookies.get('csrftoken'));     } }); 

Comments