Django-Ajax
问题
- 使用视图通过上下文向模板传递数据,需要先加载完成模板的静态页面,再执行模型的代码,生成完整的html。返回浏览器,这个过程将页面与数据集成到了一起,扩展性差!
解决
- 通过ajax的方式获取数据,通过dom操作将数据呈现在页面上
实现
-
视图:
1
2
3
4
5
6
7
8
9
10
11
12from django.http import JsonResponse
def showStudents(request):
if request.is_ajax():
stus = Student.objects.all()
list = []
for stu in stus:
list.append({"name": stu.name, "age": stu.age})
return JsonResponse({"data": list})
else:
return render(request, "myApp/showStudents.html") -
页面:
-
$.get()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<html lang="en">
<head>
<meta charset="UTF-8">
<title>学生信息</title>
<script type="text/javascript" src="/static/js/jquery-3.1.1.min.js"></script>
<body>
<button id="btn">查看学生</button>
<ul id="stulist"></ul>
<script type="text/javascript">
$(function () {
$("#btn").bind("click", function () {
$.get("/showStudents/", function (data, status) {
//console.log(data);
stus = data["data"];
for (var i = 0; i < stus.length; i++) {
stu = stus[i];
$li = $("<li>" + stu.name + "</li>");
$("#stulist").append($li);
}
});
});
});
</script>
</body>
</html> -
$.ajax()
(推荐使用)1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<html lang="en">
<head>
<meta charset="UTF-8">
<title>学生信息</title>
<script type="text/javascript" src="/static/js/jquery-3.1.1.min.js"></script>
<body>
<button id="btn">查看学生</button>
<ul id="stulist"></ul>
<script type="text/javascript">
$(function () {
$("#btn").bind("click", function () {
$.ajax({
type: "get",
url: "/showStudents/",
data: {"a": 1, "b": 1},
dataType: "json",
success: function (data, status) {
stus = data["data"];
for (var i = 0; i < stus.length; i++) {
stu = stus[i];
$li = $("<li>" + stu.name + "</li>");
$("#stulist").append($li);
}
}
});
});
});
</script>
</body>
</html>
-