(Django)CSRF Verification用于在Chrome中使用但不支持Firefox的AJAX请求

正如标题所述,我的(Django)CSRFvalidation在Chrome中运行但不在Firefox中,我想知道为什么我可以解决这个问题。

我有这个包含在我的base.html文件的head标记中,我的应用程序中的所有其他文件都扩展到该标记:

base.html,head标记的底部

 $(document).ready(function() { function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); 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); } } }); });  

我将这段代码放在一个名为browse.js的文件中,该文件需要向我自己的服务器发出ajax请求。

browse.js

 Template = { setup : function(){ Template.events.csrf(); // etc. etc. }, events: { csrf : function(){ function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); 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); } } }); }, //etc. etc. } //The actual ajax request Data = { api : { ajax_get_listings : function(cb){ var g, i, o, _ref; _ref = [ $('#ci').val(), $('#co').val(), $('#guests').val()], i = _ref[0], o = _ref[1], g = _ref[2]; if (g) { console.log('getting listings'); return $.ajax({ url:'/api/get_listing_items/', type: 'POST', datatype:'json', data: { available_start_date: i, available_end_date: o, max_guests: g }, success: function(d) { if (d.listings !== null){ Data.listings._results = []; console.log(d); var l = $.parseJSON( $("