Skip to content

Instantly share code, notes, and snippets.

Created March 11, 2013 09:06
Show Gist options
  • Save anonymous/5132933 to your computer and use it in GitHub Desktop.
Save anonymous/5132933 to your computer and use it in GitHub Desktop.
Djangoで面倒なことなくjQueryの$.ajaxを使いたい件 ======================================= Djangoでajaxを使うときにCSRF Tokenがないと怒られたので、$.ajaxを上書きして勝手にHTTP Headerに"X-CSRFToken"をつけて送ってやろうと思った。予想以上にうまく動いたので公開している。しかし、反省はしてない などど申しており…
//上のCoffee secript版
getCookie = (name) ->
cookieValue = null
if document.cookie and document.cookie isnt ""
cookies = document.cookie.split(";")
i = 0
while i < cookies.length
cookie = jQuery.trim(cookies[i])
# Does this cookie string begin with the name we want?
if cookie.substring(0, name.length + 1) is (name + "=")
cookieValue = decodeURIComponent(cookie.substring(name.length + 1))
break
i++
cookieValue
$.ajax_original = $.ajax
$.ajax = (ajax_data) ->
type = ajax_data.type
orig_before_send = ajax_data.beforeSend
try
csrf_token_val = getCookie("csrftoken")
catch error
return $.ajax_original(ajax_data)
return $.ajax_original(ajax_data) if (type?) and type.toLowerCase is "get"
before_send = (req) ->
if orig_before_send
orig_before_send(req)
req.setRequestHeader "X-CSRFToken", csrf_token_val
return
ajax_data.beforeSend = before_send
return $.ajax_original ajax_data
var getCookie;
getCookie = function(name) {
var cookie, cookieValue, cookies, i;
cookieValue = null;
if (document.cookie && document.cookie !== "") {
cookies = document.cookie.split(";");
i = 0;
while (i < cookies.length) {
cookie = jQuery.trim(cookies[i]);
if (cookie.substring(0, name.length + 1) === (name + "=")) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
i++;
}
}
return cookieValue;
};
$.ajax_original = $.ajax;
$.ajax = function(ajax_data) {
var before_send, csrf_token_val, orig_before_send, type;
type = ajax_data.type;
orig_before_send = ajax_data.beforeSend;
try {
csrf_token_val = getCookie("csrftoken");
} catch (error) {
return $.ajax_original(ajax_data);
}
if ((type != null) && type.toLowerCase === "get") {
return $.ajax_original(ajax_data);
}
before_send = function(req) {
if (orig_before_send) {
orig_before_send(req);
}
req.setRequestHeader("X-CSRFToken", csrf_token_val);
};
ajax_data.beforeSend = before_send;
return $.ajax_original(ajax_data);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment