ajax请求携带tooken_9 HTML&JS等前端知识系列之Ajax post请求带有token向Django请求

我们 在母板上写入这段代码:

// 个人定义大函数,不是重点,可以忽略

$(document).ready(function(){

get_sys_load();

var active_node = $("#mainnav-menu a[href='{{ request.path }}']");

active_node.parent().addClass("active-link");

if (active_node.parent().parent().hasClass("collapse")){

active_node.parent().parent().addClass("in");

}

});//end doc ready

// 个人定义大函数,不是重点,可以忽略

function get_sys_load(){

$.ajax({

url: "{% url 'get_server_host_status' %}",

type: "GET",

dataType: "json",

success: function(callback){

for( i in callback){

console.log(i,callback[i]);

$('#'+ i +'_display').text(callback[i]);

$('#'+ i +'_width').text(callback[i]);

$('#'+ i +'_attr').css('width',callback[i]+'%')

}// end for

},// end sucess func

error: function(callback){

alert(callback)

}// end error func

})

}

// 这个才是重点的代码,必须写

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;

}

// 这个才是重点的代码,必须写

function csrfSafeMethod(method) {

// these HTTP methods do not require CSRF protection

return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));

}

csrftoken = getCookie('csrftoken');

$.ajaxSetup({ //添加头部信息,csrftoken, 把token塞入头部

beforeSend: function(xhr, settings) {

if (!csrfSafeMethod(settings.type) && !this.crossDomain) {

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

}

}

});

{% block bottom-js %}

{% endblock %}

我们在子板上调用这端js代码,调用的前提是子板的html页面必须嵌套了这个 csrf_token, 代码如下

html页面的代码:

==================

{% csrf_token %}

==================

======JQuery代码 =======

{% block bottom-js %}

function run_cmd(){ //由于 ajaxSetup 设置好了token,所以我们可以直接提交数据了!

var input_cmd = $('textarea').val();

$.ajax({

url:"{% url 'put_cmd' %}",

type:'POST',

dataType:'json',

data:{'host_id':$('#host_id').text(),'minion_name':$('#minion_id').text(),'cmd':input_cmd},

success: function(callback){

console.log(callback)

}, // end success

error: function (callback) {

console.log(callback);

$('code').append(callback)

}

})

}

function show_result(content){

}

{% endblock %}


版权声明:本文为weixin_39780962原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。