Django CSRF check failing with an Ajax POST request

前端 未结 22 1414
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-22 03:46

I could use some help complying with Django\'s CSRF protection mechanism via my AJAX post. I\'ve followed the directions here:

http://docs.djangoproject.com/en/dev/r

22条回答
  •  既然无缘
    2020-11-22 04:13

    If your form posts correctly in Django without JS, you should be able to progressively enhance it with ajax without any hacking or messy passing of the csrf token. Just serialize the whole form and that will automatically pick up all your form fields including the hidden csrf field:

    $('#myForm').submit(function(){
        var action = $(this).attr('action');
        var that = $(this);
        $.ajax({
            url: action,
            type: 'POST',
            data: that.serialize()
            ,success: function(data){
                console.log('Success!');
            }
        });
        return false;
    });
    

    I've tested this with Django 1.3+ and jQuery 1.5+. Obviously this will work for any HTML form, not just Django apps.

提交回复
热议问题