Ajax請求
目錄
1.ajax請求使用
2.增加任務列表功能(只有查看和新增)
3.代碼展示集合
這篇文章, 要開始講關于ajax請求的內容了。這個和以前文章中寫道的Vue框架里面的axios請求, 很相似。后端代碼, 會有一些細節點, 跟前幾節文章寫的有些區別。
一、ajax請求使用
我們先在templates文件夾下面新建ajax_data文件夾, 然后再創建ajax_data.html文件。
我們先講ajax使用的方法:
$.ajax({//請求的目標地址url: "/demo/one/",// 請求類型type:"post",// 表單數據data:{sign: "45z6x4c65qf4c4c5z",type: "text"},//請求成功后,接受目標函數的數據success:function (res){// 這里面需要寫請求成功之后, 需要做的事情console.log(res);}
})
說完ajax請求后, 我們需要寫關于ajax使用的代碼:
編輯ajax_data.html:
{% extends "index/model_tmp.html" %}{% block content %}<div class="container"><h1>Ajax演示-one</h1><input type="button" id="button-one" class="btn btn-success" value="點我"><table border="1" class="table"><thead><th>分類</th><th>名稱</th><th>最高價</th><th>最低價</th><th>平均價</th><th>產地</th></thead><tbody id="tBody"></tbody></table><h1>Ajax演示-two</h1><input type="text" id="username" placeholder="請輸入賬號"><input type="password" id="password" placeholder="請輸入密碼"><input type="button" id="button-two" class="btn btn-success" value="點我"></div>
{% endblock %}{% block js %}<script>$(function () {bindBtnOne();bindBtnTwo();})function bindBtnOne() {$("#button-one").click(function () {$.ajax({//請求的目標地址url: "/demo/one/",// 請求類型type:"post",// 表單數據data:{sign: "45z6x4c65qf4c4c5z",type: "text"},//請求成功后,接受目標函數的數據success:function (res){//獲取dict_data當中list所對于的值var list = res.list;var htmlStr = "";for (var i=0; i<list.length;i++){// emp相當于dict_data[list]當中的每一個字典var emp = list[i];//每次循環的時候,向頁面添加一行六列htmlStr += "<tr>";htmlStr += "<td>"+emp.prodCat+"</td>";htmlStr += "<td>"+emp.prodName+"</td>";htmlStr += "<td>"+emp.highPrice+"</td>";htmlStr += "<td>"+emp.lowPrice+"</td>";htmlStr += "<td>"+emp.avgPrice+"</td>";htmlStr += "<td>"+emp.place+"</td>";htmlStr += "</tr>";document.getElementById("tBody").innerHTML = htmlStr;}}})})}function bindBtnTwo() {$("#button-two").click(function () {$.ajax({url:"/demo/two/",type:"post",data:{username:$("#username").val(),password:$("#password").val(),},success:function (res){//alert(res)alert(res.status)}})})}</script>
{% endblock %}
這里面有兩個ajax請求, 第一個是通過點擊按鈕來獲取后端數據完成ajax請求, 最后我們把數據放在tbody標簽里面顯示, 第二個是通過判斷賬號密碼兩個輸入框里面的內容, 是否包含在賬號數據表里面, 如果有, 那就返回true, 否則就返回false。后端代碼的邏輯, 會在后面寫道。
我們在views里面創建Ajax_data.py:
Ajax_data.py代碼:
from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.views.decorators.csrf import csrf_exempt# Create your views here.
def demo_list(request):return render(request, "ajax_data/ajax_data.html")@csrf_exempt
def demo_one(request):dict_data = {"current": 1,"limit": 20,"count": 129705,"list": [{"id": 1724017,"prodName": "大白菜","prodCatid": 1186,"prodCat": "蔬菜","prodPcatid": "null","prodPcat": "","lowPrice": "0.4","highPrice": "0.55","avgPrice": "0.48","place": "冀魯豫鄂","specInfo": "","unitInfo": "斤","pubDate": "2024-12-31 00:00:00","status": "null","userIdCreate": 138,"userIdModified": "null","userCreate": "admin","userModified": "null","gmtCreate": "null","gmtModified": "null"},{"id": 1724016,"prodName": "娃娃菜","prodCatid": 1186,"prodCat": "蔬菜","prodPcatid": "null","prodPcat": "","lowPrice": "0.65","highPrice": "0.75","avgPrice": "0.7","place": "豫","specInfo": "","unitInfo": "斤","pubDate": "2024-12-31 00:00:00","status": "null","userIdCreate": 138,"userIdModified": "null","userCreate": "admin","userModified": "null","gmtCreate": "null","gmtModified": "null"},{"id": 1724015,"prodName": "小白菜","prodCatid": 1186,"prodCat": "蔬菜","prodPcatid": "null","prodPcat": "","lowPrice": "1.0","highPrice": "1.2","avgPrice": "1.1","place": "冀","specInfo": "","unitInfo": "斤","pubDate": "2024-12-31 00:00:00","status": "null","userIdCreate": 138,"userIdModified": "null","userCreate": "admin","userModified": "null","gmtCreate": "null","gmtModified": "null"},{"id": 1724014,"prodName": "圓白菜","prodCatid": 1186,"prodCat": "蔬菜","prodPcatid": "null","prodPcat": "","lowPrice": "0.55","highPrice": "1.4","avgPrice": "0.98","place": "冀鄂魯","specInfo": "甘藍","unitInfo": "斤","pubDate": "2024-12-31 00:00:00","status": "null","userIdCreate": 138,"userIdModified": "null","userCreate": "admin","userModified": "null","gmtCreate": "null","gmtModified": "null"},{"id": 1724013,"prodName": "紫甘藍","prodCatid": 1186,"prodCat": "蔬菜","prodPcatid": "null","prodPcat": "","lowPrice": "2.3","highPrice": "2.4","avgPrice": "2.35","place": "冀蘇","specInfo": "","unitInfo": "斤","pubDate": "2024-12-31 00:00:00","status": "null","userIdCreate": 138,"userIdModified": "null","userCreate": "admin","userModified": "null","gmtCreate": "null","gmtModified": "null"},{"id": 1724012,"prodName": "芹菜","prodCatid": 1186,"prodCat": "蔬菜","prodPcatid": "null","prodPcat": "","lowPrice": "1.2","highPrice": "1.4","avgPrice": "1.3","place": "魯","specInfo": "","unitInfo": "斤","pubDate": "2024-12-31 00:00:00","status": "null","userIdCreate": 138,"userIdModified": "null","userCreate": "admin","userModified": "null","gmtCreate": "null","gmtModified": "null"},{"id": 1724011,"prodName": "西芹","prodCatid": 1186,"prodCat": "蔬菜","prodPcatid": "null","prodPcat": "","lowPrice": "1.6","highPrice": "2.0","avgPrice": "1.8","place": "魯遼","specInfo": "","unitInfo": "斤","pubDate": "2024-12-31 00:00:00","status": "null","userIdCreate": 138,"userIdModified": "null","userCreate": "admin","userModified": "null","gmtCreate": "null","gmtModified": "null"},{"id": 1724010,"prodName": "菠菜","prodCatid": 1186,"prodCat": "蔬菜","prodPcatid": "null","prodPcat": "","lowPrice": "1.2","highPrice": "1.5","avgPrice": "1.35","place": "魯冀","specInfo": "","unitInfo": "斤","pubDate": "2024-12-31 00:00:00","status": "null","userIdCreate": 138,"userIdModified": "null","userCreate": "admin","userModified": "null","gmtCreate": "null","gmtModified": "null"},{"id": 1724009,"prodName": "萵筍","prodCatid": 1186,"prodCat": "蔬菜","prodPcatid": "null","prodPcat": "","lowPrice": "1.5","highPrice": "1.9","avgPrice": "1.7","place": "魯","specInfo": "","unitInfo": "斤","pubDate": "2024-12-31 00:00:00","status": "null","userIdCreate": 138,"userIdModified": "null","userCreate": "admin","userModified": "null","gmtCreate": "null","gmtModified": "null"},{"id": 1724008,"prodName": "團生菜","prodCatid": 1186,"prodCat": "蔬菜","prodPcatid": "null","prodPcat": "","lowPrice": "2.5","highPrice": "3.5","avgPrice": "3.0","place": "云冀","specInfo": "","unitInfo": "斤","pubDate": "2024-12-31 00:00:00","status": "null","userIdCreate": 138,"userIdModified": "null","userCreate": "admin","userModified": "null","gmtCreate": "null","gmtModified": "null"},{"id": 1724007,"prodName": "羅馬生菜","prodCatid": 1186,"prodCat": "蔬菜","prodPcatid": "null","prodPcat": "","lowPrice": "3.0","highPrice": "3.3","avgPrice": "3.15","place": "云","specInfo": "","unitInfo": "斤","pubDate": "2024-12-31 00:00:00","status": "null","userIdCreate": 138,"userIdModified": "null","userCreate": "admin","userModified": "null","gmtCreate": "null","gmtModified": "null"},{"id": 1724006,"prodName": "散葉生菜","prodCatid": 1186,"prodCat": "蔬菜","prodPcatid": "null","prodPcat": "","lowPrice": "2.0","highPrice": "2.5","avgPrice": "2.25","place": "遼冀京","specInfo": "","unitInfo": "斤","pubDate": "2024-12-31 00:00:00","status": "null","userIdCreate": 138,"userIdModified": "null","userCreate": "admin","userModified": "null","gmtCreate": "null","gmtModified": "null"},{"id": 1724005,"prodName": "油菜","prodCatid": 1186,"prodCat": "蔬菜","prodPcatid": "null","prodPcat": "","lowPrice": "1.2","highPrice": "1.5","avgPrice": "1.35","place": "皖川京魯","specInfo": "","unitInfo": "斤","pubDate": "2024-12-31 00:00:00","status": "null","userIdCreate": 138,"userIdModified": "null","userCreate": "admin","userModified": "null","gmtCreate": "null","gmtModified": "null"},{"id": 1724004,"prodName": "香菜","prodCatid": 1186,"prodCat": "蔬菜","prodPcatid": "null","prodPcat": "","lowPrice": "2.0","highPrice": "2.5","avgPrice": "2.25","place": "冀","specInfo": "","unitInfo": "斤","pubDate": "2024-12-31 00:00:00","status": "null","userIdCreate": 138,"userIdModified": "null","userCreate": "admin","userModified": "null","gmtCreate": "null","gmtModified": "null"},{"id": 1724003,"prodName": "茴香","prodCatid": 1186,"prodCat": "蔬菜","prodPcatid": "null","prodPcat": "","lowPrice": "2.0","highPrice": "2.5","avgPrice": "2.25","place": "冀","specInfo": "","unitInfo": "斤","pubDate": "2024-12-31 00:00:00","status": "null","userIdCreate": 138,"userIdModified": "null","userCreate": "admin","userModified": "null","gmtCreate": "null","gmtModified": "null"},{"id": 1724002,"prodName": "韭菜","prodCatid": 1186,"prodCat": "蔬菜","prodPcatid": "null","prodPcat": "","lowPrice": "2.0","highPrice": "2.8","avgPrice": "2.4","place": "冀粵","specInfo": "","unitInfo": "斤","pubDate": "2024-12-31 00:00:00","status": "null","userIdCreate": 138,"userIdModified": "null","userCreate": "admin","userModified": "null","gmtCreate": "null","gmtModified": "null"},{"id": 1724001,"prodName": "苦菊","prodCatid": 1186,"prodCat": "蔬菜","prodPcatid": "null","prodPcat": "","lowPrice": "1.6","highPrice": "2.2","avgPrice": "1.9","place": "遼冀","specInfo": "","unitInfo": "斤","pubDate": "2024-12-31 00:00:00","status": "null","userIdCreate": 138,"userIdModified": "null","userCreate": "admin","userModified": "null","gmtCreate": "null","gmtModified": "null"},{"id": 1724000,"prodName": "油麥菜","prodCatid": 1186,"prodCat": "蔬菜","prodPcatid": "null","prodPcat": "","lowPrice": "2.2","highPrice": "3.0","avgPrice": "2.6","place": "京冀","specInfo": "","unitInfo": "斤","pubDate": "2024-12-31 00:00:00","status": "null","userIdCreate": 138,"userIdModified": "null","userCreate": "admin","userModified": "null","gmtCreate": "null","gmtModified": "null"},{"id": 1723999,"prodName": "散菜花","prodCatid": 1186,"prodCat": "蔬菜","prodPcatid": "null","prodPcat": "","lowPrice": "2.0","highPrice": "3.8","avgPrice": "2.9","place": "陜云豫","specInfo": "","unitInfo": "斤","pubDate": "2024-12-31 00:00:00","status": "null","userIdCreate": 138,"userIdModified": "null","userCreate": "admin","userModified": "null","gmtCreate": "null","gmtModified": "null"},{"id": 1723998,"prodName": "綠菜花","prodCatid": 1186,"prodCat": "蔬菜","prodPcatid": "null","prodPcat": "","lowPrice": "2.3","highPrice": "2.8","avgPrice": "2.55","place": "蘇鄂浙","specInfo": "","unitInfo": "斤","pubDate": "2024-12-31 00:00:00","status": "null","userIdCreate": 138,"userIdModified": "null","userCreate": "admin","userModified": "null","gmtCreate": "null","gmtModified": "null"}]}return JsonResponse(dict_data)@csrf_exempt
def demo_two(request):dict_data = {"status": True}return JsonResponse(dict_data)
demo_one函數里面的dict_data里面的數據, 就是當前端點擊按鈕的時候, 就會去向后端發起請求, 請求成功以后, 將數據返回給前端, 并展示到前端的頁面上。
demo_two函數里面的dict_data里面的數據, 就是把status里面的布爾值傳遞給前端, 這個布爾值就代表判斷賬號密碼的是否在賬戶數據庫表格里面存在的意思, 這個邏輯, 我們會在下一篇文章, 具體寫關于賬號密碼判斷的邏輯。
還有, 這里面用了@csrf_exempt, 是因為在前端, 沒有寫form表單, 之前我們寫前端的時候, 都是有form表單, 然后在里面寫上post方法, 里面有csrf_token, 但是這里不一樣, 用到了ajax請求, 里面type也是post, 所以我們沒有在html里面寫csrf_token, 而是把這個驗證, 寫到了后端代碼里面。這就是和之前寫的代碼, 有小小的區別, 但代碼的意思都是差不多的。在用@csrf_exempt,之前, 需要導入包:from django.views.decorators.csrf import csrf_exempt。
這里面有個叫JsonResponse, 意思就是把傳進去的參數, 以json格式返回。之后前端請求到的數據, 就是json格式的數據了。
二、 增加任務列表功能(只有查看和新增)
首先, 我們需要先增加任務數據庫表格, 這個是毋庸置疑的。
models.py:
class Task(models.Model):title = models.CharField(verbose_name="標題", max_length=64)level_choice = {(1, "臨時任務"),(2, "普通任務"),(3, "重要任務"),(4, "緊急任務")}level = models.SmallIntegerField(verbose_name="任務級別", choices=level_choice)detail = models.TextField(verbose_name="任務內容")user = models.ForeignKey(verbose_name="負責人", to="UserInfo", on_delete=models.CASCADE, null=True, blank=True)times = models.DateField(verbose_name="開始時間")code_choices = {(1, "未完成"),(2, "正在處理"),(3, "已完成")}code = models.SmallIntegerField(verbose_name="任務狀態", choices=code_choices)
然后在項目對應的目錄下, 執行python manage.py makemigrations
和python manage.py migrate
這兩行代碼。
接著, 我們在templates里面創建task_data.html文件。
task_data.html:
{% extends "index/model_tmp.html" %}{% block content %}<div class="container"><div class="panel panel-success"><div class="panel-heading"><h3 class="panel-title">添加任務</h3></div><div class="panel-body"><div class="form-group"><form id="formAdd">{% for filed in form %}<div class="col-xs-6"><label for="exampleInputEmail1">{{ filed.label }}</label>{{ filed }}</div>{% endfor %}<div class="col-xs-12"><button type="button" id="button-add" class="btn btn-success">提交</button></div></form></div></div></div></div><div class="container"><div class="panel panel-success"><div class="panel-heading"><h3 class="panel-title">任務展示</h3></div><div class="panel-body"><table class="table table-bordered"><thead><tr><th>任務ID</th><th>任務標題</th><th>任務級別</th><th>任務內容</th><th>任務時間</th><th>任務狀態</th><th>任務負責人</th><th>操作</th></tr></thead><tbody>{% for data in queryset %}<tr><th>{{ data.id }}</th><th>{{ data.title }}</th><th>{{ data.get_level_display }}</th><th>{{ data.detail }}</th><th>{{ data.times }}</th><th>{{ data.get_code_display }}</th><th>{{ data.user.name }}</th></tr>{% endfor %}</tbody></table></div></div></div>
{% endblock %}{% block js %}<script>$(function (){bindBtnEvent();})function bindBtnEvent() {$("#button-add").click(function () {$.ajax({url :"/task/add/",type:"post",data:$("#formAdd").serialize(),dataType:"JSON",success:function (res){alert("添加成功")}})})}</script>
{% endblock %}
我們這里把添加和展示頁面, 都寫在同一個頁面上面了。
在views里面新建一個task_data.py:
task_data.py代碼:
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import render
from project_one import models
from django import forms# Create your views here.
class taskModelForm(forms.ModelForm):class Meta:model = models.Taskfields = '__all__'def __init__(self, *args, **kwargs):super(taskModelForm, self).__init__(*args, **kwargs)for item, field in self.fields.items():field.widget.attrs['class'] = 'form-control'field.widget.attrs['autocomplete'] = 'off'@csrf_exempt
def task_list(request):queryset = models.Task.objects.all()form = taskModelForm()content = {'form': form, "queryset": queryset}return render(request, "task_data/task_list.html", content)@csrf_exempt
def task_add(request):form = taskModelForm(request.POST)if form.is_valid():form.save()dict_data = {"status": True}return JsonResponse(dict_data)dict_data = {"status": False}return JsonResponse(dict_data)
task_list是展示任務的內容, task_add是添加任務的內容。
在task_add里面, dict_data的status的值, 是根據數據是否添加成功來決定的, 當數據添加成功的時候, dict_data的status的值為true, 反之就為false。
最后配置下路由:
urls.py:
"""project_simple URL ConfigurationThe `urlpatterns` list routes URLs to views. For more information please see:https://docs.djangoproject.com/en/4.1/topics/http/urls/
Examples:
Function views1. Add an import: from my_app import views2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views1. Add an import: from other_app.views import Home2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf1. Import the include() function: from django.urls import include, path2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from project_one.views import depart, user, assets, admin_role, login, Ajax_data, task_dataurlpatterns = [path("task/list/", task_data.task_list, name="task_list"),path("task/add/", task_data.task_add, name="task_add"),
]
我們不要忘記在model_tmp.html里面添加ajax請求和任務列表:
model_tmp.html:
<li class="dropdown">{% if request.unicom_role == 3 %}<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true"aria-expanded="false">平臺用戶<span class="caret"></span></a>{% endif %}<ul class="dropdown-menu"><li><a href="/admin_list/">登錄賬號</a></li><li><a href="/demo/list/">ajax請求</a></li></ul>
</li>
<li class="active"><a href="/task/list/">任務列表</a></li>
運行結果:
點擊平臺用戶里面的ajax請求:
點擊按鈕:
請求成功:
然后在下面的輸入框里面隨便輸入內容:
點擊按鈕:
由于我們在后端代碼里面沒有寫到判斷賬號密碼的邏輯, 所以它這里一直返回的是true, 這個問題, 會在下一篇文章, 里面寫道。
接著再點擊任務列表:
上面填寫內容并提交:
彈窗, 顯示添加成功:
然后再刷新下網頁:
我們發現, 數據添加成功。
三、代碼展示集合
前端:
ajax_data.html:
{% extends "index/model_tmp.html" %}{% block content %}<div class="container"><h1>Ajax演示-one</h1><input type="button" id="button-one" class="btn btn-success" value="點我"><table border="1" class="table"><thead><th>分類</th><th>名稱</th><th>最高價</th><th>最低價</th><th>平均價</th><th>產地</th></thead><tbody id="tBody"></tbody></table><h1>Ajax演示-two</h1><input type="text" id="username" placeholder="請輸入賬號"><input type="password" id="password" placeholder="請輸入密碼"><input type="button" id="button-two" class="btn btn-success" value="點我"></div>
{% endblock %}{% block js %}<script>$(function () {bindBtnOne();bindBtnTwo();})function bindBtnOne() {$("#button-one").click(function () {$.ajax({//請求的目標地址url: "/demo/one/",// 請求類型type:"post",// 表單數據data:{sign: "45z6x4c65qf4c4c5z",type: "text"},//請求成功后,接受目標函數的數據success:function (res){//獲取dict_data當中list所對于的值var list = res.list;var htmlStr = "";for (var i=0; i<list.length;i++){// emp相當于dict_data[list]當中的每一個字典var emp = list[i];//每次循環的時候,向頁面添加一行六列htmlStr += "<tr>";htmlStr += "<td>"+emp.prodCat+"</td>";htmlStr += "<td>"+emp.prodName+"</td>";htmlStr += "<td>"+emp.highPrice+"</td>";htmlStr += "<td>"+emp.lowPrice+"</td>";htmlStr += "<td>"+emp.avgPrice+"</td>";htmlStr += "<td>"+emp.place+"</td>";htmlStr += "</tr>";document.getElementById("tBody").innerHTML = htmlStr;}}})})}function bindBtnTwo() {$("#button-two").click(function () {$.ajax({url:"/demo/two/",type:"post",data:{username:$("#username").val(),password:$("#password").val(),},success:function (res){//alert(res)alert(res.status)}})})}</script>
{% endblock %}
task_data.html:
{% extends "index/model_tmp.html" %}{% block content %}<div class="container"><div class="panel panel-success"><div class="panel-heading"><h3 class="panel-title">添加任務</h3></div><div class="panel-body"><div class="form-group"><form id="formAdd">{% for filed in form %}<div class="col-xs-6"><label for="exampleInputEmail1">{{ filed.label }}</label>{{ filed }}</div>{% endfor %}<div class="col-xs-12"><button type="button" id="button-add" class="btn btn-success">提交</button></div></form></div></div></div></div><div class="container"><div class="panel panel-success"><div class="panel-heading"><h3 class="panel-title">任務展示</h3></div><div class="panel-body"><table class="table table-bordered"><thead><tr><th>任務ID</th><th>任務標題</th><th>任務級別</th><th>任務內容</th><th>任務時間</th><th>任務狀態</th><th>任務負責人</th><th>操作</th></tr></thead><tbody>{% for data in queryset %}<tr><th>{{ data.id }}</th><th>{{ data.title }}</th><th>{{ data.get_level_display }}</th><th>{{ data.detail }}</th><th>{{ data.times }}</th><th>{{ data.get_code_display }}</th><th>{{ data.user.name }}</th></tr>{% endfor %}</tbody></table></div></div></div>
{% endblock %}{% block js %}<script>$(function (){bindBtnEvent();})function bindBtnEvent() {$("#button-add").click(function () {$.ajax({url :"/task/add/",type:"post",data:$("#formAdd").serialize(),dataType:"JSON",success:function (res){alert("添加成功")}})})}</script>
{% endblock %}
model_tmp.html:
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title><link rel="stylesheet" href="{% static 'css/bootstrap.css' %}">{% block css %}{% endblock %}
</head>
<body>
<div class="navbar navbar-default"><div class="container"><!-- Brand and toggle get grouped for better mobile display --><div class="navbar-header"><button type="button" class="navbar-toggle collapsed" data-toggle="collapse"data-target="#bs-example-navbar-collapse-1" aria-expanded="false"><span class="sr-only">Toggle navigation</span><span class="icon-bar"></span><span class="icon-bar"></span><span class="icon-bar"></span></button><a class="navbar-brand" href="#">管理系統</a></div><!-- Collect the nav links, forms, and other content for toggling --><div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"><ul class="nav navbar-nav">{% if request.unicom_role == 1 %}<li class="active"><a href="/depart/">部門頁面</a></li><li class="active"><a href="/user/">員工頁面</a></li>{% elif request.unicom_role == 3%}<li class="active"><a href="/depart/">部門頁面</a></li><li class="active"><a href="/user/">員工頁面</a></li><li class="active"><a href="/assets_list/">資產頁面</a></li>{% endif %}
{# <li class="active"><a href="/depart/">部門頁面</a></li>#}
{# <li class="active"><a href="/user/">員工頁面</a></li>#}
{# <li class="active"><a href="/assets_list/">資產頁面</a></li>#}<li class="dropdown">{% if request.unicom_role == 3 %}<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true"aria-expanded="false">平臺用戶<span class="caret"></span></a>{% endif %}<ul class="dropdown-menu"><li><a href="/admin_list/">登錄賬號</a></li><li><a href="/demo/list/">ajax請求</a></li></ul></li><li class="active"><a href="/task/list/">任務列表</a></li></ul><ul class="nav navbar-nav navbar-right"><li class="dropdown"><a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true"aria-expanded="false">歡迎-->{{ request.session.info.username }}<span class="caret"></span></a><ul class="dropdown-menu"><li><a href="/logout/">退出登錄</a></li></ul></li></ul></div><!-- /.navbar-collapse --></div><!-- /.container-fluid -->
</div>{% block content %}
{% endblock %}
<script src="{% static 'js/jquery3.7.1.js' %}"></script>
<script src="{% static 'js/bootstrap.js' %}"></script>
{% block js %}
{% endblock %}
</body>
</html>
后端:
models.py:
from django.db import models# Create your models here.
class Department(models.Model):title = models.CharField(verbose_name="部門名稱", max_length=255)def __str__(self):return self.titleclass UserInfo(models.Model):name = models.CharField(verbose_name="姓名", max_length=255)gender_choices = ((1, "男"), (2, "女"))gender = models.SmallIntegerField(verbose_name="性別", choices=gender_choices)salary = models.IntegerField(verbose_name="薪水")age = models.IntegerField(verbose_name="年齡")create_time = models.DateField(verbose_name="入職時間")department = models.ForeignKey(verbose_name="部門", max_length=255, to="Department", to_field="id",on_delete=models.CASCADE, null=True, blank=True)def __str__(self):return self.nameclass Assets(models.Model):mobile = models.CharField(verbose_name="手機號", max_length=11)status_code_choice = ((1, "已使用"),(2, "未使用"))status = models.SmallIntegerField(verbose_name="狀態", choices=status_code_choice)create_time = models.DateField(verbose_name="創建時間")user = models.ForeignKey(to="UserInfo", to_field="id", verbose_name="使用者", on_delete=models.SET_NULL, null=True, blank=True)price = models.CharField(verbose_name="價格", max_length=10)class AdminRole(models.Model):username = models.CharField(verbose_name="用戶名", max_length=32)password = models.CharField(verbose_name="密碼", max_length=64)password_choice = ((1, "員工"),(2, "領導"),(3, "管理員"))role = models.SmallIntegerField(verbose_name="角色", choices=password_choice)class Task(models.Model):title = models.CharField(verbose_name="標題", max_length=64)level_choice = {(1, "臨時任務"),(2, "普通任務"),(3, "重要任務"),(4, "緊急任務")}level = models.SmallIntegerField(verbose_name="任務級別", choices=level_choice)detail = models.TextField(verbose_name="任務內容")user = models.ForeignKey(verbose_name="負責人", to="UserInfo", on_delete=models.CASCADE, null=True, blank=True)times = models.DateField(verbose_name="開始時間")code_choices = {(1, "未完成"),(2, "正在處理"),(3, "已完成")}code = models.SmallIntegerField(verbose_name="任務狀態", choices=code_choices)
Ajax_data.py:
from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.views.decorators.csrf import csrf_exempt# Create your views here.
def demo_list(request):return render(request, "ajax_data/ajax_data.html")@csrf_exempt
def demo_one(request):dict_data = {"current": 1,"limit": 20,"count": 129705,"list": [{"id": 1724017,"prodName": "大白菜","prodCatid": 1186,"prodCat": "蔬菜","prodPcatid": "null","prodPcat": "","lowPrice": "0.4","highPrice": "0.55","avgPrice": "0.48","place": "冀魯豫鄂","specInfo": "","unitInfo": "斤","pubDate": "2024-12-31 00:00:00","status": "null","userIdCreate": 138,"userIdModified": "null","userCreate": "admin","userModified": "null","gmtCreate": "null","gmtModified": "null"},{"id": 1724016,"prodName": "娃娃菜","prodCatid": 1186,"prodCat": "蔬菜","prodPcatid": "null","prodPcat": "","lowPrice": "0.65","highPrice": "0.75","avgPrice": "0.7","place": "豫","specInfo": "","unitInfo": "斤","pubDate": "2024-12-31 00:00:00","status": "null","userIdCreate": 138,"userIdModified": "null","userCreate": "admin","userModified": "null","gmtCreate": "null","gmtModified": "null"},{"id": 1724015,"prodName": "小白菜","prodCatid": 1186,"prodCat": "蔬菜","prodPcatid": "null","prodPcat": "","lowPrice": "1.0","highPrice": "1.2","avgPrice": "1.1","place": "冀","specInfo": "","unitInfo": "斤","pubDate": "2024-12-31 00:00:00","status": "null","userIdCreate": 138,"userIdModified": "null","userCreate": "admin","userModified": "null","gmtCreate": "null","gmtModified": "null"},{"id": 1724014,"prodName": "圓白菜","prodCatid": 1186,"prodCat": "蔬菜","prodPcatid": "null","prodPcat": "","lowPrice": "0.55","highPrice": "1.4","avgPrice": "0.98","place": "冀鄂魯","specInfo": "甘藍","unitInfo": "斤","pubDate": "2024-12-31 00:00:00","status": "null","userIdCreate": 138,"userIdModified": "null","userCreate": "admin","userModified": "null","gmtCreate": "null","gmtModified": "null"},{"id": 1724013,"prodName": "紫甘藍","prodCatid": 1186,"prodCat": "蔬菜","prodPcatid": "null","prodPcat": "","lowPrice": "2.3","highPrice": "2.4","avgPrice": "2.35","place": "冀蘇","specInfo": "","unitInfo": "斤","pubDate": "2024-12-31 00:00:00","status": "null","userIdCreate": 138,"userIdModified": "null","userCreate": "admin","userModified": "null","gmtCreate": "null","gmtModified": "null"},{"id": 1724012,"prodName": "芹菜","prodCatid": 1186,"prodCat": "蔬菜","prodPcatid": "null","prodPcat": "","lowPrice": "1.2","highPrice": "1.4","avgPrice": "1.3","place": "魯","specInfo": "","unitInfo": "斤","pubDate": "2024-12-31 00:00:00","status": "null","userIdCreate": 138,"userIdModified": "null","userCreate": "admin","userModified": "null","gmtCreate": "null","gmtModified": "null"},{"id": 1724011,"prodName": "西芹","prodCatid": 1186,"prodCat": "蔬菜","prodPcatid": "null","prodPcat": "","lowPrice": "1.6","highPrice": "2.0","avgPrice": "1.8","place": "魯遼","specInfo": "","unitInfo": "斤","pubDate": "2024-12-31 00:00:00","status": "null","userIdCreate": 138,"userIdModified": "null","userCreate": "admin","userModified": "null","gmtCreate": "null","gmtModified": "null"},{"id": 1724010,"prodName": "菠菜","prodCatid": 1186,"prodCat": "蔬菜","prodPcatid": "null","prodPcat": "","lowPrice": "1.2","highPrice": "1.5","avgPrice": "1.35","place": "魯冀","specInfo": "","unitInfo": "斤","pubDate": "2024-12-31 00:00:00","status": "null","userIdCreate": 138,"userIdModified": "null","userCreate": "admin","userModified": "null","gmtCreate": "null","gmtModified": "null"},{"id": 1724009,"prodName": "萵筍","prodCatid": 1186,"prodCat": "蔬菜","prodPcatid": "null","prodPcat": "","lowPrice": "1.5","highPrice": "1.9","avgPrice": "1.7","place": "魯","specInfo": "","unitInfo": "斤","pubDate": "2024-12-31 00:00:00","status": "null","userIdCreate": 138,"userIdModified": "null","userCreate": "admin","userModified": "null","gmtCreate": "null","gmtModified": "null"},{"id": 1724008,"prodName": "團生菜","prodCatid": 1186,"prodCat": "蔬菜","prodPcatid": "null","prodPcat": "","lowPrice": "2.5","highPrice": "3.5","avgPrice": "3.0","place": "云冀","specInfo": "","unitInfo": "斤","pubDate": "2024-12-31 00:00:00","status": "null","userIdCreate": 138,"userIdModified": "null","userCreate": "admin","userModified": "null","gmtCreate": "null","gmtModified": "null"},{"id": 1724007,"prodName": "羅馬生菜","prodCatid": 1186,"prodCat": "蔬菜","prodPcatid": "null","prodPcat": "","lowPrice": "3.0","highPrice": "3.3","avgPrice": "3.15","place": "云","specInfo": "","unitInfo": "斤","pubDate": "2024-12-31 00:00:00","status": "null","userIdCreate": 138,"userIdModified": "null","userCreate": "admin","userModified": "null","gmtCreate": "null","gmtModified": "null"},{"id": 1724006,"prodName": "散葉生菜","prodCatid": 1186,"prodCat": "蔬菜","prodPcatid": "null","prodPcat": "","lowPrice": "2.0","highPrice": "2.5","avgPrice": "2.25","place": "遼冀京","specInfo": "","unitInfo": "斤","pubDate": "2024-12-31 00:00:00","status": "null","userIdCreate": 138,"userIdModified": "null","userCreate": "admin","userModified": "null","gmtCreate": "null","gmtModified": "null"},{"id": 1724005,"prodName": "油菜","prodCatid": 1186,"prodCat": "蔬菜","prodPcatid": "null","prodPcat": "","lowPrice": "1.2","highPrice": "1.5","avgPrice": "1.35","place": "皖川京魯","specInfo": "","unitInfo": "斤","pubDate": "2024-12-31 00:00:00","status": "null","userIdCreate": 138,"userIdModified": "null","userCreate": "admin","userModified": "null","gmtCreate": "null","gmtModified": "null"},{"id": 1724004,"prodName": "香菜","prodCatid": 1186,"prodCat": "蔬菜","prodPcatid": "null","prodPcat": "","lowPrice": "2.0","highPrice": "2.5","avgPrice": "2.25","place": "冀","specInfo": "","unitInfo": "斤","pubDate": "2024-12-31 00:00:00","status": "null","userIdCreate": 138,"userIdModified": "null","userCreate": "admin","userModified": "null","gmtCreate": "null","gmtModified": "null"},{"id": 1724003,"prodName": "茴香","prodCatid": 1186,"prodCat": "蔬菜","prodPcatid": "null","prodPcat": "","lowPrice": "2.0","highPrice": "2.5","avgPrice": "2.25","place": "冀","specInfo": "","unitInfo": "斤","pubDate": "2024-12-31 00:00:00","status": "null","userIdCreate": 138,"userIdModified": "null","userCreate": "admin","userModified": "null","gmtCreate": "null","gmtModified": "null"},{"id": 1724002,"prodName": "韭菜","prodCatid": 1186,"prodCat": "蔬菜","prodPcatid": "null","prodPcat": "","lowPrice": "2.0","highPrice": "2.8","avgPrice": "2.4","place": "冀粵","specInfo": "","unitInfo": "斤","pubDate": "2024-12-31 00:00:00","status": "null","userIdCreate": 138,"userIdModified": "null","userCreate": "admin","userModified": "null","gmtCreate": "null","gmtModified": "null"},{"id": 1724001,"prodName": "苦菊","prodCatid": 1186,"prodCat": "蔬菜","prodPcatid": "null","prodPcat": "","lowPrice": "1.6","highPrice": "2.2","avgPrice": "1.9","place": "遼冀","specInfo": "","unitInfo": "斤","pubDate": "2024-12-31 00:00:00","status": "null","userIdCreate": 138,"userIdModified": "null","userCreate": "admin","userModified": "null","gmtCreate": "null","gmtModified": "null"},{"id": 1724000,"prodName": "油麥菜","prodCatid": 1186,"prodCat": "蔬菜","prodPcatid": "null","prodPcat": "","lowPrice": "2.2","highPrice": "3.0","avgPrice": "2.6","place": "京冀","specInfo": "","unitInfo": "斤","pubDate": "2024-12-31 00:00:00","status": "null","userIdCreate": 138,"userIdModified": "null","userCreate": "admin","userModified": "null","gmtCreate": "null","gmtModified": "null"},{"id": 1723999,"prodName": "散菜花","prodCatid": 1186,"prodCat": "蔬菜","prodPcatid": "null","prodPcat": "","lowPrice": "2.0","highPrice": "3.8","avgPrice": "2.9","place": "陜云豫","specInfo": "","unitInfo": "斤","pubDate": "2024-12-31 00:00:00","status": "null","userIdCreate": 138,"userIdModified": "null","userCreate": "admin","userModified": "null","gmtCreate": "null","gmtModified": "null"},{"id": 1723998,"prodName": "綠菜花","prodCatid": 1186,"prodCat": "蔬菜","prodPcatid": "null","prodPcat": "","lowPrice": "2.3","highPrice": "2.8","avgPrice": "2.55","place": "蘇鄂浙","specInfo": "","unitInfo": "斤","pubDate": "2024-12-31 00:00:00","status": "null","userIdCreate": 138,"userIdModified": "null","userCreate": "admin","userModified": "null","gmtCreate": "null","gmtModified": "null"}]}return JsonResponse(dict_data)@csrf_exempt
def demo_two(request):dict_data = {"status": True}return JsonResponse(dict_data)
task_data.py:
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import render
from project_one import models
from django import forms# Create your views here.
class taskModelForm(forms.ModelForm):class Meta:model = models.Taskfields = '__all__'def __init__(self, *args, **kwargs):super(taskModelForm, self).__init__(*args, **kwargs)for item, field in self.fields.items():field.widget.attrs['class'] = 'form-control'field.widget.attrs['autocomplete'] = 'off'@csrf_exempt
def task_list(request):queryset = models.Task.objects.all()form = taskModelForm()content = {'form': form, "queryset": queryset}return render(request, "task_data/task_list.html", content)@csrf_exempt
def task_add(request):form = taskModelForm(request.POST)if form.is_valid():form.save()dict_data = {"status": True}return JsonResponse(dict_data)dict_data = {"status": False}return JsonResponse(dict_data)
urls.py:
"""project_simple URL ConfigurationThe `urlpatterns` list routes URLs to views. For more information please see:https://docs.djangoproject.com/en/4.1/topics/http/urls/
Examples:
Function views1. Add an import: from my_app import views2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views1. Add an import: from other_app.views import Home2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf1. Import the include() function: from django.urls import include, path2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from project_one.views import depart, user, assets, admin_role, login, Ajax_data, task_dataurlpatterns = [# path('admin/', admin.site.urls),path("", depart.index, name="index"),path("depart/", depart.depart, name="depart"),path("depart/add/", depart.add_depart, name="add_depart"),path("depart/<int:nid>/modify/", depart.depart_modify, name="depart_modify"),path("depart/<int:nid>/del/", depart.del_depart, name="del_depart"),path("user/", user.user_info, name="user_info"),path("user/add/", user.user_add, name="user_add"),path("user/<int:nid>/modify/", user.user_modify, name="user_modify"),path("user/<int:nid>/del/", user.user_del, name="user_del"),path("user/add/modelform", user.user_add_modelform, name="user_add_modelform"),path("user/<int:nid>/modify/modelform", user.user_modify_modelform, name="user_modify_modelform"),path("assets_list/", assets.assets, name="assets"),path("assets/add/", assets.assets_add, name="assets_add"),path("assets/<int:nid>/modify/", assets.assets_modify, name="assets_modify"),path("assets/<int:nid>/del/", assets.assets_del, name="assets_del"),path("admin_list/", admin_role.admin, name="admin"),path("admin/add/", admin_role.admin_add, name="admin_add"),path("admin/<int:nid>/modify/", admin_role.admin_modify, name="admin_modify"),path("admin/<int:nid>/reset/pwd/", admin_role.admin_reset_pwd, name="admin_reset_pwd"),path("admin/<int:nid>/del/", admin_role.admin_del, name="admin_del"),path("login/", login.login, name="login"),path("logout/", login.logout, name="logout"),path("image/code/", login.image_code, name="image_code"),path("demo/list/", Ajax_data.demo_list, name="demo_list"),path("demo/one/", Ajax_data.demo_one, name="demo_one"),path("demo/two/", Ajax_data.demo_two, name="demo_two"),path("task/list/", task_data.task_list, name="task_list"),path("task/add/", task_data.task_add, name="task_add"),
]
好了, 關于django框架里面的ajax請求使用的內容, 就到此為止了。這個ajax使用, 和Vue框架里面的axios差不多, 還有一些后端代碼, 有些寫法和之前的不一樣, 可以和前面文章寫的后端代碼進行對比學習!!!
以上就是Django框架里面的ajax請求使用的所有內容了, 如果有哪里不懂的地方,可以把問題打在評論區, 歡迎大家在評論區交流!!!
如果我有寫錯的地方, 望大家指正, 也可以聯系我, 讓我們一起努力, 繼續不斷的進步.
學習是個漫長的過程, 需要我們不斷的去學習并掌握消化知識點, 有不懂或概念模糊不理解的情況下,一定要趕緊的解決問題, 否則問題只會越來越多, 漏洞也就越老越大.
人生路漫漫, 白鷺常相伴!!!