django中使用POST方法 使用ajax后出现“CSRF token missing or incorrect”

这个是因为在django的ajax中默认添加了token,因此需要在cookie中增加token头信息。

首先使用JavaScript函数获取token:

function getCookie(name){
    var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");

    if(arr=document.cookie.match(reg))

        return unescape(arr[2]);
    else
        return null;
}

然后在POST的xmlHttpRequest对象中增加一个请求头:

xmlhttp.setRequestHeader("X-CSRFToken",getCookie("csrftoken"));

 

posted @ 2018-06-25 09:29  在左手  阅读(1982)  评论(0编辑  收藏  举报