index.html:
+
=
$("#b1").on("click", function () {
$.ajax({
url: "/ajax_add/",
type: "POST",
data: {"i1": $("#i1").val(), "i2": $("#i2").val()},
success: function (data) {
$("#i3").val(data);
}
})
});
views.py:
from django.shortcuts import render, HttpResponse
def index(request):
return render(request, "index.html")
def ajax_add(request):
num1 = request.POST.get("i1")
num2 = request.POST.get("i2")
ret = int(num1) + int(num2)
return HttpResponse(ret)
访问,http://127.0.0.1:8000/index/
输入两组数,点击提交
这里需要验证 csrf token
方法一:
在 index.html 中添加 csrf token
访问,http://127.0.0.1:8000/index/
右键 -> 检查
取到 name
修改 index.html:
{% csrf_token %}
+
=
$("#b1").on("click", function () {
var csrfToken = $("[name='csrfmiddlewaretoken']").val();
$.ajax({
url: "/ajax_add/",
type: "POST",
data: {"i1": $("#i1").val(), "i2": $("#i2").val(), "csrfmiddlewaretoken": csrfToken},
success: function (data) {
$("#i3").val(data);
}
})
});
运行
方法二:
在 /static/ 目录下创建 test.js:
// 获取 cookie
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'); // 获取 cookie 中的 csrf token
// 哪些请求方法不需要用到 csrf token
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
// 要用到 csrf token
$.ajaxSetup({
beforeSend: function (xhr, settings) { // 在发送请求之前
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken); // 在请求头中添加 csrf token
}
}
});
在 index.html 中导入该 js 文件
{% csrf_token %}
+
=
$("#b1").on("click", function () {
$.ajax({
url: "/ajax_add/",
type: "POST",
data: {"i1": $("#i1").val(), "i2": $("#i2").val()},
success: function (data) {
$("#i3").val(data);
}
})
});
运行结果: