LoginSignup
34
26

More than 5 years have passed since last update.

DjangoでAjaxする時の注意点

Last updated at Posted at 2014-09-17

DjangoでAjax

通常Djangoは{% csrf_token %}をテンプレートで書いていないとcsrftokenをクッキーにセットしない。

確実にセットするためには

from django.views.decorators.csrf import ensure_csrf_cookie

@ensure_csrf_cookie
def view(request):
    pass

みたいな感じで使う。

JS

以下コピペ

// using jQuery
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({
    crossDomain: false, // obviates need for sameOrigin test
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type)) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});

使う

$.ajax({
    type: 'POST',
    url: "/ajax/",
}).done(function(data){
    alert('success!!');
}).fail(function(data){
    alert('error!!!');
});
34
26
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
34
26