【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 %}
相关推荐
2601_9620652519 小时前
从零创建一个 Django 项目
后端·python·django
千里码aicood21 小时前
Django 基于Django的电脑推荐与分析可视化系统设计与实现
python·django·电脑
汤姆yu1 天前
基于Django的学习资料共享与智能推荐系统
后端·python·django·毕业设计·学习资料共享
Mr数据杨1 天前
【Codex】用学生入学评估模块建立新生能力画像
android·java·javascript·django·codex·项目开发
Mr数据杨1 天前
【Codex】用部门管理模块维护组织架构与管理层级
架构·django·codex·项目开发
Mr数据杨1 天前
【Codex】用附件管理模块统一维护系统文件资源
django·codex·项目开发
IT毕设实战小研1 天前
基于安卓的空气质量查询系统
android·大数据·vue.js·爬虫·python·django·课程设计
Mr数据杨2 天前
【Codex】用座位划分模块优化班级空间与课堂管理
django·codex·项目开发
Mr数据杨2 天前
【Codex】用系统配置工作台集中维护平台运行参数
django·codex·项目开发
Mr数据杨2 天前
【Codex】用学生生活日常模块记录校园生活过程
django·生活·codex·项目开发