爲什麼?因爲您的方法附加到您在beforeSend
中未引用的對象。你基本上可以把它想象這樣的:
$.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
}
});
在源代碼中實際的代碼如下所示:
// 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();
}
哪裏s
是一些jQuery對象,而不是在任何可用的範圍。
至於如何解決這個問題,你需要在其他地方聲明你的函數或者將你的選項分配給一個可引用的對象。
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);
}
}
};
就這麼你知道,(至少)GET請求** DO **需要CSRF保護 – christophetd