(第五周3)P57Ajax任务管理实例
有较多涉及到JavaScript的知识,会套用就行
源代码:
class TaskModelForm(BootStrapModelForm):
class Meta:
model = models.Task
fields = "__all__"
widgets = {
"detail": forms.Textarea,
}
def task_list(request):
form = TaskModelForm()
return render(request, 'task_list.html', {'form': form})
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def task_ajax(request):
print(request.GET)
print(request.POST)
data_dict = {
"status": True,
"data": [11, 22, 33, 45],
}
# import json
# json_string = json.dumps(data_dict)
# return HttpResponse(json)
# 可以利用django自带模块转成json格式
from django.http import JsonResponse
return JsonResponse(data_dict)
@csrf_exempt
def task_add(request):
print(request.POST)
import json
# 基于ModelForm校验数据
form = TaskModelForm(data=request.POST)
if form.is_valid():
form.save()
data_dict = {
"status": True,
}
json_string = json.dumps(data_dict)
return HttpResponse(json_string)
# else:
print(type(form.errors))
from django.forms.utils import ErrorDict
# 可以直接用内部方法将错误信息转换成json
data_dict = {
"status": False,
"error": form.errors,
}
json_string = json.dumps(data_dict, ensure_ascii=False)
return HttpResponse(json_string)
{% extends 'layout.html' %}
{% block content %}
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">表单</div>
<div class="panel-body">
<form id="formAdd">
<div class="clearfix">
{% for field in form %}
<div class="col-xs-6">
<div class="form-group" style="position: relative; margin-bottom: 20px;">
<label>
{{ field.label }}
<span style="color: red">{{ field.errors.0 }}</span>
</label>
{{ field }}
<span class="error_msg" style="color: red; position: absolute;"></span>
</div>
</div>
{% endfor %}
<div class="col-xs-12">
<button type="button" id="btnAdd" class="btn btn-default">提交</button>
</div>
</div>
</form>
</div>
</div>
<div>
<hr/>
<h1>Ajax案例</h1>
<h3>示例1</h3>
{# <input type="button" class="btn btn-primary" value="点击" onclick="clickMe();"/>#}
<input type="button" class="btn btn-primary" id="btn1" value="点击1"/>
<h3>示例2</h3>
<input type="text" id="nameUser" placeholder="姓名">
<input type="text" id="ageUser" placeholder="年龄">
<input type="button" class="btn btn-primary" id="btn2" value="点击2"/>
<h3>示例3</h3>
<form id="form3">
<p><input type="text" name="user" placeholder="姓名"></p>
<p><input type="text" name="age" placeholder="年龄"></p>
<p><input type="text" name="email" placeholder="邮箱"></p>
<p><input type="text" name="more" placeholder="年龄"></p>
<p><input type="button" class="btn btn-primary" id="btn3" value="点击3"/></p>
</form>
</div>
</div>
{% endblock %}
{% block js %}
<script type="text/javascript">
{#基于dom方法绑定事件#}
{#function clickMe(){#}
{# console.log("点击了按钮");#}
{# $.ajax({#}
{# url: '/task_ajax',#}
{#type: 'get',#}
{# type: 'post',#}
{# data: {#}
{# n1: 123,#}
{# n2: 'abc',#}
{# },#}
{# success: function (res){#}
{# console.log(res);#}
{# }#}
{# })#}
{# } #}
$(function () {
//页面框架加载完成后自动执行
bindBtn1Event();
bindBtn2Event();
bindBtn3Event();
})
function bindBtn1Event() {
$("#btn1").click(function () {
$.ajax({
url: '/task_ajax/',
type: 'post',
data: {
n1: 123,
n2: 'abc',
},
{#将后端传过来JSON的转成字符串反序列化成JSON对象,使得前端可以直接调用#}
dataType: "JSON",
success: function (res) {
console.log(res);
console.log(res.data)
}
})
})
}
function bindBtn2Event() {
$("#btn2").click(function () {
$.ajax({
url: '/task_ajax/',
type: 'post',
data: {
name: $("#nameUser").val(),
age: $("#ageUser").val(),
},
{#将后端传过来JSON的转成字符串反序列化成JSON对象,使得前端可以直接调用#}
dataType: "JSON",
success: function (res) {
console.log(res);
console.log(res.data)
}
})
})
}
function bindBtn3Event() {
$("#btn3").click(function () {
$.ajax({
url: '/task_ajax/',
type: 'post',
{#示例3使用表单就不用一个个的传值了#}
data: $("#form3").serialize(),
{#将后端传过来JSON的转成字符串反序列化成JSON对象,使得前端可以直接调用#}
dataType: "JSON",
success: function (res) {
console.log(res);
console.log(res.data);
}
})
})
}
</script>
<script type="text/javascript">
$(function () {
//页面框架加载完成后自动执行
bindBtnAddEvent();
})
function bindBtnAddEvent() {
$("#btnAdd").click(function () {
{#首先清空上一次的错误信息#}
$(".error_msg").empty();
$.ajax({
url: '/task_add/',
type: 'post',
{#示例3使用表单就不用一个个的传值了#}
data: $("#formAdd").serialize(),
{#将后端传过来JSON的转成字符串反序列化成JSON对象,使得前端可以直接调用#}
dataType: "JSON",
success: function (res) {
if (res.status) {
alter("添加成功");
} else {
console.log(res.error);
$.each(res.error, function (name, data){
console.log(name, data);
$("#id_"+name).next().text(data[0]);
})
}
}
})
})
}
</script>
{% endblock %}