【Django】教程-10-ajax请求Demo,结合使用

【Django】教程-1-安装+创建项目+目录结构介绍
【Django】教程-2-前端-目录结构介绍
【Django】教程-3-数据库相关介绍
【Django】教程-4-一个增删改查的Demo
【Django】教程-5-ModelForm增删改查+规则校验【正则+钩子函数】
【Django】教程-6-搜索框-条件查询前后端
【Django】教程-7-分页,默认使用django的
【Django】教程-8-页面时间组件
【Django】教程-9-登录+退出

16. ajax

16.1 GET请求

login目录text.html

html 复制代码
{% extends 'login/layout.html' %}
{% block content %}
    <h3>示例 1</h3>
    <input id="btn1" type="button" class="btn-primary" value="点击1" onclick="clickMe();"/>

{% endblock %}

{% block js %}
	<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script type="text/javascript">
        function clickMe() {
            console.log("进来了")

            $.ajax({
                url: '/task/ajax/',
                type: 'get',
                data: {
                    n1: 123,
                    n2: 456
                },
                success: function (res) {
                    console.log(res);
                }
            })
        }
    </script>
{% endblock %}

views目录account.py文件

python 复制代码
def task_list(r):
    "显示一个页面,用于ajax"
    return render(r, 'login/test.html')
def task_ajax(req):
    print(req.method)
    print(req.GET.get('n1'))
    return HttpResponse("成功了!")

urls.py

python 复制代码
from django.urls import path
from appTang.views import department_views, user_views, admin_views, account

# 映射关系,视图--->函数
urlpatterns = [
    path('task/list', account.task_list),
    path('task/ajax/', account.task_ajax),

]

16.1 POST请求

html 复制代码
{% block js %}
    <script type="text/javascript">
        function clickMe() {
            console.log("进来了")
            $.ajax({
                url: '/task/ajax/',
                type: 'post',
                data: {
                    n1: 123,
                    n2: 456
                },
                success: function (res) {
                    console.log(res);
                }
            })
        }
    </script>
{% endblock %}
python 复制代码
from django.views.decorators.csrf import csrf_exempt

@csrf_exempt # 对单个函数关掉,csrf校验
def task_ajax(req):
    print(req.method)
    print(req.POST)
    return HttpResponse("成功了!")

16.3 绑定事件

html 复制代码
{% block js %}
	<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script type="text/javascript">
        $(function (){
            // 页面框架加载完成之后,代码自动执行
            bindBtnEvent();

        })
        function bindBtnEvent(){
            {# 可以,发送ajax请求 #}
            $.ajax({
                url: '/task/ajax/',
                type: 'post',
                data: {
                    n1: 123,
                    n2: 456
                },
                success: function (res) {
                    console.log(res);
                }
            })
        }
    </script>
{% endblock %}

16.4 ajax请求返回值

ajax 通常都是返回json格式数据

python 复制代码
data_dict = {"status": True, "data": [11, 22, 33, 44]}
# 两种方式都可以
# json_string = json.dumps(data_dict)
# return HttpResponse(json_string)

return JsonResponse(data_dict)
js 复制代码
$.ajax({
    url: '/task/ajax/',
    type: 'post',
    data: {
        n1: 123,
        n2: 456
    },
    {# 将返回值,变成json对象 ,后面可以直接 .属性#}
    dataType: "JSON", 
    success: function (res) {
        console.log(res);
    	console.log(res.data);
    }
})

16.5 表单提交

两种方式,一种form,一种一个一个的val

$("#form3").serialize()

n1: $("#txtUser").val(),

html 复制代码
{% extends 'login/layout.html' %}
{% block content %}
    <div>
        <div class="container">
            <h3>示例2 </h3>
            <input type="text" id="txtUser" placeholder="姓名"/>
            <input type="text" id="txtAge" placeholder="年龄"/>
            <input type="button" id="btn2" class="btn btn-primary" value="点击2"/>

            <h3>示例3 </h3>
            <form id="form3">
                <input type="text" name="username" placeholder="姓名"/>
                <input type="text" name="age" placeholder="年龄"/>
                <input type="text" name="email" placeholder="邮箱"/>
                <input type="text" name="more" placeholder="简介"/>
            </form>
            <input type="button" id="btn3" class="btn btn-primary" value="点击3"/>
        </div>
    </div>
{% endblock %}
{% block js %}
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script type="text/javascript">

        $(function () {
            bindBtn2Event();
            bindBtn3Event();
        })

        function bindBtn2Event() {
            $("#btn2").click(function () {
                $.ajax({
                    url: '/task/ajax/',
                    type: 'post',
                    data: {
                        n1: $("#txtUser").val(),
                        n2: $("#txtAge").val(),
                    },
                    dataType: "JSON",
                    success: function (res) {
                        console.log(res);
                        console.log(res.status);
                    }
                })
            })

        }

        function bindBtn3Event() {
            $("#btn3").click(function () {
                $.ajax({
                    url: '/task/ajax/',
                    type: 'post',
                    data: $("#form3").serialize(),
                    dataType: "JSON",
                    success: function (res) {
                        console.log(res);
                        console.log(res.data);
                    }
                })
            })

        }
    </script>
{% endblock %}
相关推荐
Elaine3364 小时前
基于Django框架的静态个人名片网站设计
后端·python·django·mvt
2601_961194027 小时前
考研资料电子版|下载|pdf
java·python·考研·eclipse·django·pdf·pygame
我有2只猫1 天前
LabelStudio二次开发
人工智能·python·django·ocr
大刚测试开发实战1 天前
TestHub测试平台整体功能简介
django·llm·测试
Wonderful U2 天前
Python+Django实战:打造智能生鲜果蔬进销存管理系统(采购入库、库存预警、销售开单、毛利统计)
数据库·python·django
*neverGiveUp*3 天前
初步了解Django框架
开发语言·python·django
2601_961194023 天前
2026四级词汇闪过电子版|高频词+真题词速记PDF
数据库·python·django·pdf·pygame
Wonderful U3 天前
基于Python+Django+MySQL构建个人任务管理系统:告别零散记录,实现高效日程管理
python·mysql·django
Wonderful U3 天前
基于Python+Django的文件预览与转换系统:从架构设计到完整实现
后端·python·django
*neverGiveUp*3 天前
Django ORM
后端·python·django