Django处理PUT请求有几个点需要注意:
CSRF配置
为了防止跨站攻击,Django默认会对POST/PUT/DELETE这几种操作进行csrf token检查。POST可以将其放到post的参数中,但Django对PUT/DELETE只能通过检查Header的方式检查csrf token。
所以应当在HTML中确认发送之前配置了Ajax的头:
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);
}
}
});
通过Ajax发送PUT/DELETE请求
需要注意的几个地方:
设置type为PUT,DELETE同理
-
url必须以/结尾
$.ajax({ url: dbUrl + tableName + "/", // Append back slash for put request type: "PUT", data: {"key": key, "field": field, "field-value": input.value}, success: function(result) { input.style.backgroundColor = "#b3ffb3"; }, error: function(event, XMLHttpRequest, ajaxOptions, thrownError) { input.style.backgroundColor = "#ffad99"; input.value = oldValue } });
后台处理参数
Django对于PUT/DELETE请求并没有像POST/GET那样有一个字典结构。我们需要手动处理request.body获取参数:
from django.http import QueryDict
put = QueryDict(request.body)
key = put.get('key')
field = put.get('field')
field_value = put.get('field-value')