Bootstrap

【Django】ajax和django接口交互(获取新密码)

一、需求

1. 效果图

在这里插入图片描述

二、实验

1. 写get接口后端

  • 写views
import string
import random
def getnewpwd(request):
    words = list(
        string.ascii_lowercase
        +string.ascii_uppercase
        +string.digits
        +string.punctuation
    )
    random.shuffle(words)
    result = "".join(words[:20])
    return HttpResponse(result)
  • 写urls

urlpatterns = [
    path("getnewpwd/",views.getnewpwd),
]
  • 测试后端接口
    在这里插入图片描述

2. 写html后端

  • 写views
def getnewpwdhtml(request):
    return render(request,"getnewpwd.html",{})
  • 写urls
urlpatterns = [
    path("getnewpwdhtml/",views.getnewpwdhtml),
]

3. 写前端

{% load static %}
<!DOCTYPE html>
<html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet"
            href="{% static "antapp/bootstrap/bootstrap.min.css" %}">
        <title>Document</title>
    </head>
    <body>
        <div class="row" style="margin-top: 20px;margin-left: 40px;">
            <button type="button" id="getnewpwd" class="btn btn-success" style="margin-left: 5px;">获取新密码</button>
        </div>
        <div class="row"  style="margin-top: 20px; margin-left: 40px;">
            <div id="shownewpwd" class="alert alert-primary" role="alert"> </div>
        </div>
        <script src="{% static "antapp/bootstrap/jquery.min.js" %}"></script>
        <script src="{% static "antapp/bootstrap/bootstrap.bundle.min.js" %}"></script>
        <script>
            $(function(){
                $("#getnewpwd").click(function(){
                    $.ajax({
                        url:"/getnewpwd/",
                        type:"get",
                        success:function(result){
                            $("#shownewpwd").html(result)
                        }
                        
                    })
                })

            })
        </script>
    </body>
</html>

4. 测试

在这里插入图片描述

在这里插入图片描述

;