1.CSRF
如果ajax用get获取数据的话,就可以不用考虑csrf的问题。
但是如果用post提交数据的话,就必修对CSRF做处理。
一种方法是在ajax提交的数据中加入csrf_token
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
具体参照Django官方文档https://docs.djangoproject.com/en/3.0/ref/csrf/
或者在django代码加修饰器@csrf_exempt
@csrf_exempt
def log_in_app(request):
...
return JsonResponse({"success": 1})
2.送信数据类型(datatype)
如果没有指定送信类型为Json的话,直接从request.POST里面取数据就可以了。
但如果数据类型如果是Json的话,需要json模块把数据取出来,而不能直接从request.POST取
def tag_suggestions(request):
data = json.loads(request.body)
print(data)
return JsonResponse({"success": 1})