Py学习  »  问与答

Django ajax post {%csrf_token%}的问题究竟怎么解决?

SAMZZZ • 9 年前 • 4880 次点击  

这个问题搞得我好苦恼,网上查了一大堆答案,结果没有能解决的(可能是因为我的代码错了)。希望大家能帮我解答这个问题。问题描述如下: 一开始写js,我是这样天真的写的。

function getModifiedDistrict(id,name){
district_id= id;
district_name= name;
$(".col-md-9").empty();
var str=" <form action='' method='post' class='form-horizontal'>"+
"{% csrf_token %}"+
" <div class='form-group'>"+
"   <label for='areaname' class='control-label col-md-2'>校区名</label>"+
"       <div class='col-md-4'>"+
"           <input type='text' value='"+district_name+"' autofocus='autofocus' class='form-control' id='modifyDistrict'/>"+
"       </div>"+
"   </div>"+
" <div class='form-group col-md-2'>"+
"   <input type='submit'  style='margin-left: 329px;' class='btn btn-primary' value='保存修改'>"+
"</div>"+
"</form>";
$(".col-md-9").append(str);

} 结果,当然就是错了。网页把"{% csrf_token %}"当作一个要显示在网页上的字符来处理了,而且没有达到POST的功能。后来改用ajax,如下:

function getModifiedDistrict(id,name){
district_id= id;
district_name= name;
$(".col-md-9").empty();
var str=" <form action='' method='post' class='form-horizontal'>"+
" <div class='form-group'>"+
"   <label for='areaname' class='control-label col-md-2'>校区名</label>"+
"       <div class='col-md-4'>"+
"           <input type='text' value='"+district_name+"' autofocus='autofocus' class='form-control' id='modifyDistrict'/>"+
"       </div>"+
"   </div>"+
" <div class='form-group col-md-2'>"+
"   <input type='submit'  style='margin-left: 329px;' class='btn btn-primary' onclick= modifyDistrict(district_id, district_name) value='保存修改'>"+
"</div>"+
"</form>";
$(".col-md-9").append(str);}

function modifyDistrict(id, name){
district_id= id;
district_name= name;
$.ajaxSend({
    url:'setupAjax/updateDistrictActionAjax.action',
    type:'post',
    dataType:'json',
    data:{"district_id":district_id,"district_name":$("#modifyDistrict").val()},
    success:function(result){
        if(result.result=='success')
        alert('修改成功!');
        else alert('修改失败!'+ result.errorMsg);

        $(".tab-pane").empty();
        getModifiedDistrict();
    },
    error:function(){
        alert('服务器错误');
    }
});

}

接下来就出现了重要的问题:因为用了POST,而且无法像模板那样加"{% csrf_token %}",所以出现:Forbidden (403) CSRF verification failed. Request aborted。 据说是有办法在ajax里面处理csrftoken的,但是究竟该怎么解决呢?希望大家能够针对我的代码进行解答,谢谢~~~这个问题搞得我真的很苦恼。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/1500
 
4880 次点击  
文章 [ 7 ]  |  最新文章 9 年前
小白不白
Reply   •   1 楼
小白不白    9 年前

参数加上 csrfmiddlewaretoken: "{{csrf_token}}"

HelloSam
Reply   •   2 楼
HelloSam    9 年前

@Ziv_Luther-weibo 问题已解决,谢谢~~~

Ziv_Luther-weibo
Reply   •   3 楼
Ziv_Luther-weibo    9 年前
$(document).ready(function(){
$.ajaxSetup({ 
  beforeSend: function(xhr, settings) {
      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;
      }
      if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {

          xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
      }
  }

}); });

Ziv_Luther-weibo
Reply   •   4 楼
Ziv_Luther-weibo    9 年前

你这段代码是写在一个js文件里吗?

拼接的form,没看到任何的动态内容,为什么要拼接呀,可以直接写在html里面,隐藏起来,需要的时候,显示就好了吧。

{% csrf_token %} 这种标识只能用在模板里,才有作用。

下面这段代码应该贴在调用$.ajax 之前才能起作用。 $(document).ready(function(){ $.ajaxSetup({ beforeSend: function(xhr, settings) { 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; } if (!(/^http:./.test(settings.url) || /^https:./.test(settings.url))) {

          xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
      }
  }

}); });

HelloSam
Reply   •   5 楼
HelloSam    9 年前

后来发现,csrftoken问题在<form>标签那里已经出问题了。所以我把<form>标签里的method='POST'去掉,代码如下:

function getModifiedDistrict(id,name){
district_id= id;
district_name= name;
$(".col-md-9").empty();
setupAjax();
var str=" <form class='form-horizontal'>"+
" <div class='form-group'>"+
"   <label for='areaname' class='control-label col-md-2'>校区名</label>"+
"       <div class='col-md-4'>"+
"           <input type='text' value='"+district_name+"' autofocus='autofocus' class='form-control' id='modifyDistrict'/>"+
"       </div>"+
"   </div>"+
" <div class='form-group col-md-2'>"+
"   <input type='submit'  style='margin-left: 329px;' onclick=(modifyDistrict(district_id)) class='btn btn-primary' value='保存修改'>"+
"</div>"+
"</form>";
$(".col-md-9").append(str);

}

function modifyDistrict(id){
district_id= id;
$.ajax({
    url:'setupAjax/updateDistrictActionAjax.action',
    type:'post',
    dataType:'json',
    data:{"district_id":district_id,"district_name":$("#modifyDistrict").val()},
    success:function(result){
        if(result.result=='success')
        alert('修改成功!');
        else alert('修改失败!'+ result.errorMsg);
        $(".tab-pane").empty();
        getModifiedDistrict();
    },
    error:function(){
        alert('服务器错误');
    }
});

}

但是这样达不到ajax向后台请求的效果……我该怎么办?

HelloSam
Reply   •   6 楼
HelloSam    9 年前

@skye212 试了,发现还是不行~我ajax里面是$.ajax(...),而不是$.post(...)

skye212
Reply   •   7 楼
skye212    9 年前

/csrftoken设置,否则无法调用$.post/ function setupAjax() { $.ajaxSetup({ beforeSend: function (xhr, settings) { var csrftoken = $.cookie('csrftoken'); xhr.setRequestHeader("X-CSRFToken", csrftoken); } }); }

使用方法: $(function(){ setupAjax(); $.post(...); });