2016-04-14 73 views
0

我有以下AJAX調用:調用helper方法調用

$.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不可見?

我該如何解決這個問題?

+0

就這麼你知道,(至少)GET請求** DO **需要CSRF保護 – christophetd

回答

0

嘗試this.csrfSafeMethod代替csrfSafeMethod

+1

這是行不通的。 「beforeSend」(或「ajaxSetup」中的任何方法)不會在上下文設置爲「選項」的情況下調用。 –

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

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