Django jQuery post request

后端 未结 4 1254
花落未央
花落未央 2020-12-05 03:29
$.ajax({
    url:\'/\',
    type: \"POST\",
    data: {name: \'name\', age: \'age\'},
    success:function(response){},
    complete:function(){},
    error:function         


        
相关标签:
4条回答
  • 2020-12-05 03:58

    I read on another post that you can do something like this:

    $.ajax({
        method: "POST",
        url: "{% url 'some_route' %}",
        headers: {'X-CSRFToken': '{{ csrf_token }}'},
        contentType: "application/json",
        dataType: 'json',
        data: {name:$('#id_name').val()}
    })
    .fail(function(message) {
        alert('error');
    })
    .done(function(data) {
        alert(data);
    });
    
    0 讨论(0)
  • 2020-12-05 04:09

    You need to include a CSRF (cross-site request forgery) token in your ajax call. This is well documented here: https://docs.djangoproject.com/en/dev/ref/contrib/csrf/

    or, if you want to use a quick fix, use the @csrf_exempt decorator for your view:

    from django.views.decorators.csrf import csrf_exempt
    
    @csrf_exempt
    def my_view(request):
       ...
    
    0 讨论(0)
  • 2020-12-05 04:11

    The answer to your question what you are doing wrong, is: not much!

    Django returns a 403 response (Forbidden) if an incoming POST request fails Csrf checks. You can do this through jQuery's ajaxSetup, code snippets are found here

    The reason that this DOES work on a GET request, is simply that GET requests are not checked by the csrf middleware.

    As it seems you are building a form here, another thing to consider is using class based forms. They handle get/post and also parameter validation for you. Very neat. Especially when you are making forms to edit/create/delete model instances, in which case you can embrace the power of ModelForms and CreateViews. Very neat.

    It might take some time to get the hang of those generic class based views. But it's very well worth it.

    0 讨论(0)
  • 2020-12-05 04:16

    Within a Django template you can add this...

    {% csrf_token %}
    

    Which will output something like this to your page html...

    <input type="hidden" name="csrfmiddlewaretoken" value="ckhUdNOTj88A...hfTnREALlks2kz">
    

    Then using Javascript you can simply find this input and get its value - something like this non jQuery example...

    var el = document.getElementsByName("csrfmiddlewaretoken");
    csrf_value = el[0].getAttribute("value");
    

    Lastly add the csrf_value to your jQuery AJAX post form data line like so...

    data: {name: 'name', age: 'age', csrfmiddlewaretoken: csrf_value},
    

    Here's a working jsFiddle concept: https://jsfiddle.net/vdx1Lfpc/18/

    0 讨论(0)
提交回复
热议问题