django 使用post方法出现403错误的解决办法
当采用客户端象django的服务器提交post请求时。会得到403,权限异常。因为django针对提交的请教,有校验。所以会如此。
解决办法:
导入模块:from django.views.decorators.csrf import csrf_exempt
在接收post请求的函数前面添加修饰器:@csrf_exempt
//用户必须登陆这个getCookie才会起作用
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; }
//用户必须登陆这个getCookie才会起作用 var csrftoken = getCookie('csrftoken'); $.ajax({ cache: false, type: "POST", url: "/showtable/", traditional:true, //加上此项可以传数组 dataType:'json', async: true, data:{'l1_first':l1_first}, success: function(data) { console.log(data); $('#show_tree_table').bootstrapTable('destroy'); //显示表头 并且导入数据 show_list_table(data.table_title_list,data.new_project_json); $('body').mLoading("hide"); totalpage = data.totalpage; console.log(totalpage); //进行分页 $("#pagination2").pagination({ currentPage: 1, totalPage: Math.ceil(totalpage / 20), callback: function(current) { PageNation(current); } }) }, beforeSend: function(xhr, settings) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } });