为了解决CSRF问题,我为Ajax使用了客户端设置:
$.ajaxSetup({ beforeSend: function(xhr, settings) { 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; } if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) { // Only send the token to relative URLs i.e. locally. xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')); } } });
直到今天,一切正常。但是现在我需要在发布之前做一些检查:
var check; //... $.ajax({ //... beforeSend: function(xhr){ if (check == 1){ xhr.abort(); } }, success: function(data){ //... } });
CSRF验证失败。请求中止。据我了解,我只是取消了ajaxSetup对新功能的操作。如何将这两件事结合起来?
使用$(document).ajaxSend(function(ev, jqhr, settings) { ... })代替.ajaxSetup。
$(document).ajaxSend(function(ev, jqhr, settings) { ... })
.ajaxSetup
如您所说,.ajaxSetup定义了默认处理程序,然后可以将其覆盖。使用,.ajaxSend您可以注册多个处理程序以在发送ajax请求之前触发。与自定义beforeSend处理程序配合正常。
.ajaxSend
beforeSend