Using ajax request in Django without form element

前端 未结 3 1066
北恋
北恋 2021-01-13 10:45

I\'d like to send an ajax request (via Jquery, although I think that\'s irrelevant in this situation) without using a form element in Django. According to the documentation,

相关标签:
3条回答
  • 2021-01-13 11:19

    ensure_csrf_cookie may only be a 1.4 alpha feature if you're having trouble importing it -- I can import it just fine with the same statement on trunk.

    The simplest solution here is to pass the csrf_token VALUE in the ajax call itself.

    You said you were using jQuery.

        $.ajax({
            url: "",
            type: 'POST',
            data: {
                 csrfmiddlewaretoken: '{{ csrf_token }}' // just the token value
            },
            success: function(response) {
            }
        })
    

    It appears this ensure_csrf_cookie forces the view to set the csrf cookie that would be required for use in the automatic cookie based csrf protection mechanism for jquery ajax calls described here: https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax

    0 讨论(0)
  • 2021-01-13 11:35

    You're right - this appears to be a bug in the documentation. You should be able to use csrf_exempt instead (same documentation page).

    0 讨论(0)
  • 2021-01-13 11:39

    The answer of Yuji works perfectly if you have access to the Django tag. If in your page, you already have a form that is using the tag (thus it has the hidden input field containing the CSRF) you can use:

        var formData = new FormData();
        formData.append("csrfmiddlewaretoken", $('input[name=csrfmiddlewaretoken]').val());
    
        $.ajax({
            url: "",
            type: "POST",
            data: formData,
            processData: false,
            contentType: false,
    
            success: function() {
                ...
            },
    
    0 讨论(0)
提交回复
热议问题