我有以下AJAX调用:
$.ajaxSetup({
csrfSafeMethod: function(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
},
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
我得到:
csrfSafeMethod is not defined
为什么从beforeSend
内部看不到csrfSafeMethod
?
我该怎么解决这个问题?
难道不能定义一个这样的正则函数吗:
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);
}
}
});
为什么?因为你的方法被附加到一个你在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);
}
}
};
尝试this.csrfSafeMethod
而不是csrfSafeMethod