我是Ajax的新手,想用jQuery在Django中创建一个Ajax请求,但是我被卡住了。
我从一个简单的例子开始检查它是否有效
var button = $('.any_button');
$(button).click(function() {
var button_value = $(this).val();
$.ajax({
type: "POST",
url: "/url-path/to-my/view-function/",
dataType: "json",
data: { "button_value": button_value },
beforeSend: function () {
alert("Before Send")
},
success: function () {
alert("Success");
},
error: function () {
alert("Error")
}
});
});
我已从https://docs.djangoproject.com/en/1.11/ref/csrf/
插入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;
}
var csrftoken = getCookie('csrftoken');
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);
}
}
});
我的观看功能:
from django.http import JsonResponse
def button_check(request):
data = {"message": "Message"}
return JsonResponse(data)
我的url
路径指的是views.button_check
我得到beforeSend alert
和error alert
,但我希望success alert
我错过了什么?不幸的是我无法继续。
答案 0 :(得分:2)
在jquery中尝试这样,
$.ajax({
type: "POST",
url: "/button_check/",
method: "POST",
data: { "button_value": button_value },
contentType: "application/json",
beforeSend: function () {
alert("Before Send")
},
success: function () {
alert("Success");
},
error: function () {
alert("Error")
}
});
url应该是,
url(r'button_check/', 'views.button_check'),
如果您的请求是“POST”或特定尝试,
def button_check(request):
if request.method == "POST":
data = {"message": "Message"}
return JsonResponse(data)
答案 1 :(得分:1)
您传递给jQuery.ajax的值会覆盖ajax setup:
$.ajaxSetup({
beforeSend: function(xhr, settings) {
//this will never happen because it is overridden later
alert("you will never see this.");
}
});
$.ajax({
type: "GET",
url: "/index.html",
beforeSend: function () {
console.log("another before send");
},
})
.then(x => console.log("success:",x))
.then(undefined,reject => console.error(reject));
这意味着您无法进行身份验证并丢失csrf令牌。
正如你在评论中所说;删除$ .ajax中的boforesend