Django jQuery post request

后端 未结 4 1265
花落未央
花落未央 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 04:16

    Within a Django template you can add this...

    {% csrf_token %}
    

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

    
    

    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/

提交回复
热议问题