Django框架中Ajax GET与POST请求的实战应用

简介: Django框架中Ajax GET与POST请求的实战应用

前言

    在本博客中,我们将通过登录注册两个实战案例,深入探讨如何在Django项目中使用Ajax进行网络请求以实现数据交互。同时,我们还将详细解析如何利用Cookie和Session来管理用户状态,确保用户信息的安全性和一致性。


一、跨域

跨域问题参考下面这篇文章:

跨域问题与Django解决方案:深入解析跨域原理、请求处理与CSRF防护

二、登录

1.前端html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login</title>
    <script src="./js/jquery-2.2.0.min.js"></script>
    <script>
        function fnLogin() {
            var username_label = document.getElementById('username');
            var password_label = document.getElementById('password');
            var user = {
                username: null,
                password: null,
            }
            user.username = username_label.value;
            user.password = password_label.value;
            $.ajax({
                url: "http://127.0.0.1:8000/app/login/",
                type: "POST",
                dataType: "json",
                data: user,
                xhrFields: { withCredentials: true }, //设置支持携带cookie
                success: function (response) {
                    if (response.code == '200') {
                        alert(response.message)
                        window.location.href = 'exd8_news.html';
                    } else {
                        alert(response.message)
                    }
                },
                error: function () {
                    alert("请求失败!")
                }, async: true
            })
        }
    </script>
</head>
<body>
    <input type="text" id="username" placeholder="请输入用户名:"><br>
    <input type="text" id="password" placeholder="请输入密码:"><br>
    <input type="button" value="Login" onclick="fnLogin();">
</body>
</html>

2.后端逻辑

# app/views.py
class LoginView(View):
    def post(self,request):
        username = request.POST.get('username')
        password = request.POST.get('password')
        try:
            user = UserModel.objects.get(username=username)
            if user.password == password:
                request.session['userid'] = user.id #
                print("-------------------")
                print(request.session['userid']) 
                return JsonResponse({"message": "登录成功!", "code": "200"})
            else:
                return JsonResponse({"message": "密码错误!登录失败!", "code": "201"})
        except Exception as e:
            print(e)
            return JsonResponse({"message": "用户不存在!登录失败!", "code": "202"})

三、注册

1.前端html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Register</title>
    <script src="./js/jquery-2.2.0.min.js"></script>
    <script>
        function fnRegister() {
            var username_label = document.getElementById('username');
            var phone_label = document.getElementById('phone');
            var password_label = document.getElementById('password');
            var cpassword_label = document.getElementById('cpassword');
            var user = {
                username: null,
                phone: null,
                password: null,
                cpassword: null,
            }
            user.username = username_label.value;
            user.phone = phone_label.value;
            user.password = password_label.value;
            user.cpassword = cpassword_label.value;
            $.ajax({
                url: "http://127.0.0.1:8000/app/register/",
                type: "POST",
                dataType: "json",
                data: user,
                success: function (response) {
                    if (response.code == '200') {
                        alert(response.message + "跳转到登录页面!")
                        console.log(response);
                        window.location.href = 'login.html';
                    } else {
                        alert(response.message)
                    }
                },
                error: function () {
                    console.log("请求失败!!!");
                }
            })
        }
    </script>
</head>
<body>
    用户名:<input type="text" id="username"><br>
    手机号:<input type="text" id="phone"><br>
    密码:<input type="password" id="password"><br>
    确认密码:<input type="password" id="cpassword"><br>
    <button onclick="fnRegister()">注册</button>
</body>
</html>

2.后端逻辑

# app/views.py
class RegisterView(View):
    def post(self, request):
        # 用户名username,手机号phone,密码password
        # put  delete
        # postman 测试:
        # 1.传参为raw格式时
        # 2.传参为x-www-form-urlencoded时
        print(request.POST)
        print("-------------------")
        print(request.body)
        # -------------------------------------------------
        # 1.传参为raw格式时
        # 字符串转成字典 通过decode解码
        # 使用put  delete时:
        # data = request.body.decode()
        # print("data:" + data)
        # # #***使用raw 传参数时***
        # import json
        # res_dict = json.loads(data)
        # print("username:" + res_dict.get('username'))
        #
        # username = res_dict.get('username')
        # password = res_dict.get('password')
        # phone = res_dict.get('phone')
        # cpassword = res_dict.get('cpassword')
        # -----------------------------------------------------------------
        # 2.传参为x-www-form-urlencoded时
        username = request.POST.get('username')
        password = request.POST.get('password')
        phone = request.POST.get('phone')
        cpassword = request.POST.get('cpassword')
        import re
        if re.match(r'^1[3-9]\d{9}$', phone):
            try:
                UserModel.objects.get(phone__exact=phone)
                return JsonResponse({'message': '用户已存在,请登录'})
            except:
                # 两次密码是否一致
                if password == cpassword:
                    user = UserModel()
                    user.name = username
                    user.password = password
                    user.phone = phone
                    user.save()
                    # 取决于逻辑
                    # request.session['']
                    return JsonResponse({'message': '注册成功'})
                else:
                    return JsonResponse({'message': '两次输入密码不一致'})
        else:
            return JsonResponse({'message': '手机号不满足规则'})

1.使用postman测试POST传参为raw格式时:



控制台输出:

2.使用postman测试POST传参为x-www-form-urlencoded时:



控制台输出:

最后遇到的一个小问题:

使用vscode测试前端页面时使用open in browser和open with live server,可能给会导致不同的结果,详情见下篇文章:VSCode调试揭秘:Live Server助力完美测试Cookie与Session,远超“Open in Browser”!

相关文章
|
1月前
|
存储 SQL 数据采集
Django框架的表单验证和过滤机制的原理是什么?
Django框架的表单验证和过滤机制的原理是什么?
108 73
|
2月前
|
数据采集 中间件 Python
如何在Django框架中进行输入验证和过滤?
通过综合运用这些方法,可以在 Django 框架中有效地进行输入验证和过滤,提高应用的安全性和数据质量。同时,还可以根据具体的业务需求进一步扩展和定制验证逻辑。
133 65
|
3月前
|
搜索推荐 API 开发者
Django框架和Flask框架的适用场景分别是什么?
总体而言,Django 更适合需要全面功能和大规模开发的场景,而 Flask 则更适合灵活性要求高、小型项目或特定需求的开发。当然,具体的选择还应根据项目的具体情况、团队的技术能力和偏好等因素来综合考虑。在实际应用中,开发者可以根据项目的特点和需求,灵活选择使用这两个框架,或者结合它们的优势来构建更强大的 Web 应用程序。
160 64
|
3月前
|
开发框架 搜索推荐 数据可视化
Django框架适合开发哪种类型的Web应用程序?
Django 框架凭借其强大的功能、稳定性和可扩展性,几乎可以适应各种类型的 Web 应用程序开发需求。无论是简单的网站还是复杂的企业级系统,Django 都能提供可靠的支持,帮助开发者快速构建高质量的应用。同时,其活跃的社区和丰富的资源也为开发者在项目实施过程中提供了有力的保障。
156 62
|
2月前
|
监控 安全 测试技术
Django框架的表单验证和过滤机制是否可以应对复杂的安全场景?
综上所述,Django 框架的表单验证和过滤机制在一定程度上可以应对复杂的安全场景,但需要综合运用多种手段来进一步提升安全性,以适应不断变化的安全挑战。
117 52
|
中间件 数据库 Python
Django-请求生命周期
Django-请求生命周期
108 0
|
API 网络架构 Python
源码剖析Django REST framework的请求生命周期
学习Django的时候知道,在Django请求的生命周期中,请求经过WSGI和中间件到达路由,不管是FBV还是CBV都会先执行View视图函数中的dispatch方法 REST framework是基于Django的API框架,REST framework采用的是CBV的请求模式.
1306 0
|
Python 数据库 中间件
Django中请求的生命周期
1. 概述 首先我们知道HTTP请求及服务端响应中传输的所有数据都是字符串. 在Django中,当我们访问一个的url时,会通过路由匹配进入相应的html网页中. Django的请求生命周期是指当用户在浏览器上输入url到用户看到网页的这个时间段内,Django后台所发生的事情 而Django的生命周期内到底发生了什么呢?? 1.
1250 0
|
3月前
|
设计模式 前端开发 数据库
Python Web开发:Django框架下的全栈开发实战
【10月更文挑战第27天】本文介绍了Django框架在Python Web开发中的应用,涵盖了Django与Flask等框架的比较、项目结构、模型、视图、模板和URL配置等内容,并展示了实际代码示例,帮助读者快速掌握Django全栈开发的核心技术。
266 45