在Ajax调用中调用helper方法

时间:2016-04-14 20:40:29

标签: javascript jquery ajax

我有以下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

为什么在csrfSafeMethod内无法看到beforeSend

我该如何解决这个问题?

3 个答案:

答案 0 :(得分:3)

你不能像这样定义常规函数:

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 :(得分:1)

为什么呢?因为您的方法附加到您在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);
      }
  }
};

答案 2 :(得分:0)

尝试使用this.csrfSafeMethod代替csrfSafeMethod

相关问题