(第五周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" >
<label>
{
{ field.label }}
<span >{
{ field.errors.0 }}</span>
</label>
{
{ field }}
<span class="error_msg" ></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 %}