文章目录
- urls.py
from app01 import views
urlpatterns = [
url(r'^ajax_test/$', views.ajax_test),
url(r'^calc/$', views.calc)
]
- views.py
def ajax_test(request):
return render(request, 'calc.html')
def calc(request):
print(request.POST)
i1 = int(request.POST.get("i1"))
i2 = int(request.POST.get("i2"))
i3 = int(request.POST.get("i3"))
if i1 + i2 == i3:
return HttpResponse("正确")
else:
return HttpResponse("错误")
- calc.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>calc</title>
</head>
<body>
{% csrf_token %}
<input type="text" id="i1">+<input type="text" id="i2">=<input type="text" id="i3">
<input type="button" value="ajax提交" id="b1">
<p><span id="check"></span></p>
<!--需要先下载jquery文件, 并配置静态资源目录-->
<script src="/static/jQuery/jQuery3.4.1.min.js"></script>
<script>
// 设置b1点击事件
$("#b1").click(function () {
$.ajax({
url: "/calc/", // 发送请求的 url
type: "post", // 发送请求的方式
data: {
"i1": $("#i1").val(), // val()表示取 value 属性的值, 这里拿到 id 为 i1 的值
"i2": $("#i2").val(),
"i3": $("#i3").val(),
"csrfmiddlewaretoken": $("[name='csrfmiddlewaretoken']").val()
},
success: function (res) {
// 请求被正常响应, 会自动调用执行这个函数
console.log(res);
if (res) {
$("#check").text(res); // 设置标签下的文字
}
},
error: function (err) {
// 未被正常响应, 执行这个函数
console.log(err);
}
})
})
</script>
</body>
</html>