2016-04-14 26 views

cevap

0

sadece çok gibi normal bir işlev tanımlamak Can not yerine csrfSafeMethod

+1

gerekir. 'beforeSend' (veya" ajaxSetup "ın içindeki herhangi bir yöntem)" seçenekler "e ayarlanan içerikle çağrılmaz. –

3

ait this.csrfSafeMethod deneyin:

function csrfSafeMethod(method) { 
    // these HTTP methods do not require CSRF protection 
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); 
} 

$.ajaxSetup({ 
    beforeSend: function(xhr, settings) { 
     if (!csrfSafeMethod(settings.type) && !this.crossDomain) { 
      xhr.setRequestHeader("X-CSRFToken", csrftoken); 
     } 
    } 
}); 
1

Neden? Yönteminiz, beforeSend'da başvurmadığınız bir nesneye eklendiğinden. Temelde böyle hayal edebilirsiniz:

$.ajaxSetup = function(options) { 
    var beforeSend = options.beforeSend; 
    // do stuff... 
    var xhr = getXHR(); 
    var settings = getSettings(); 
    beforeSend(xhr, settings); 
}; 

$.ajaxSetup({ 
    csrfSafeMethod: function() { ... }, 
    beforeSend: function() { 
    // `this` is the same as if I called this function in the global scope 
    // It has no reference to the `options` object 
    } 
}); 

kaynak kodunda gerçek kod şuna benzer:

s
// Allow custom headers/mimetypes and early abort 
if (s.beforeSend && 
    (s.beforeSend.call(callbackContext, jqXHR, s) === false || completed)) { 

    // Abort if not done already and return 
    return jqXHR.abort(); 
} 

herhangi mevcut kapsamda, bazı jQuery nesnesidir.

Bunu nasıl düzelteceğinize ilişkin olarak, işlevinizi başka bir yerde bildirmeniz veya seçeneklerinizi başvurulan bir nesneye atamanız gerekir.

var options = { 
    csrfSafeMethod: function(method) { 
    // these HTTP methods do not require CSRF protection 
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); 
    }, 

    beforeSend: function(xhr, settings) { 
     if (!options.csrfSafeMethod(settings.type) && !this.crossDomain) { 
      xhr.setRequestHeader("X-CSRFToken", csrftoken); 
     } 
    } 
};