利用ajax對用戶註冊進行判斷

相關配置代碼以下:
1.models.pycss

from django.db import models

# Create your models here.
GENDER = {
    ('male', '男'),
    ('female', '女'),
}
class User(models.Model):
    username=models.CharField(max_length=32,null=False)
    password=models.CharField(max_length=32,null=False)
    email = models.EmailField(null=True)
    name = models.CharField(max_length=20, null=True)
    tel = models.CharField(max_length=20, null=True)
    gender = models.CharField(max_length=20, choices=GENDER)
    birthday = models.DateTimeField(null=True)

2.settings 數據庫、static改動html

STATIC_URL = '/static/'
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "/cdnpanel/static"),
)
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'django',
        'USER': 'root',
        'HOST': 'localhost',
        'PORT': '3306',
        'PASSWORD': '123456',
    }
}

3.views服務端主程序前端

from django.core.exceptions import ValidationError
from django.db import IntegrityError
from django.shortcuts import redirect, render, HttpResponse
from cdnpanel.models import User,Domain
import json

def login(request):
    return render(request, "login.html")

def register(request):
    if request.method == "POST":
        ajax_rsp = {"status": "ok", "msg": None}
        try:
            if request.is_ajax():
                username= request.POST.get('username')
                password= request.POST.get('password')
                name= request.POST.get('name')
                email= request.POST.get('email')
                tel= request.POST.get('tel')
                gender= request.POST.get('gender')
                birthday= request.POST.get('birthday')

                if User.objects.filter(username=username).exists():
                    ajax_rsp["status"]="err"
                    ajax_rsp["msg"]="用戶已存在"
                else:
                    User.objects.create(
                        username=username,
                        password=password,
                        email=email,
                        name=name,
                        tel=tel,
                        gender=gender,
                        birthday=birthday,
                    )
        except IntegrityError:
            ajax_rsp["status"] = "err"
            ajax_rsp['msg']="性別爲必選項"
        except ValidationError:
            ajax_rsp["status"] = "err"
            ajax_rsp['msg']="日期爲必選項"
        return HttpResponse(json.dumps(ajax_rsp))
    else:
        return render(request, "register.html")

4.客戶端register頁面及其樣式mysql

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>註冊頁面</title>
    <!--    引入格式文件-->
    <link rel="stylesheet" href="/static/css/register.css">
    <style>
        .err{
            color: red;
        }
    </style>
</head>
<body>
    <div class="rg_layout">
        <div class="rg_left">
            <p>新用戶註冊</p>
            <p>USER REGISTER</p>
        </div>
        <div class="rg_center">
            <div class="rg_form">
                <form action="/register" method="post">
                {% csrf_token %}
                    <table>
                        <tr><!--label 標籤的做用是當點擊文字也會跳到文本輸出框-->
                            <!--for屬性與ID屬性對應規定 label 綁定到哪一個表單元素。-->
                            <td class="td_left"><label for="username">用戶名</label> </td>
                            <td class="td_right"><input type="text" name="username" id="username">
                                <span class="user_err err"></span>
                            </td>
                        </tr>
                        <tr>
                            <td class="td_left"><label for="password">密碼</label> </td>
                            <td class="td_right"><input type="password" name="password" id="password"> </td>
                        </tr>
                        <tr><!--label 標籤的做用是當點擊文字也會跳到文本輸出框-->
                            <td class="td_left"><label for="email">email</label> </td>
                            <td class="td_right"><input type="email" name="email" id="email"> </td>
                        </tr>
                        <tr>
                            <td class="td_left"><label for="name">姓名</label> </td>
                            <td class="td_right"><input type="text" name="name" id="name"> </td>
                        </tr>
                        <tr>
                            <td class="td_left"><label for="tel">手機號</label> </td>
                            <td class="td_right"><input type="text" name="tel" id="tel"> </td>
                        </tr>
                        <tr>
                            <td class="td_left">性別</td>
                            <td class="td_right">
                                <input type="radio" name="gender"  value="male">男
                                <input type="radio" name="gender"  value="famale">女
                                <span class="gender_err err"></span>
{#                                加個span標籤顯示錯誤信息,默認爲空值,err樣式賦予紅色字體   #}
                            </td>
                        </tr>
                        <tr>
                            <td class="td_left"><label for="birthday">出生日期</label> </td>
                            <td class="td_right"><input type="date" name="birthday" id="birthday">
                                <span class="birthday_err err"></span>
                            </td>

                        </tr>
                        <tr>
{#                            <td class="td_left"><label for="checkcode">驗證碼</label> </td>#}
{#                            <td class="td_right">#}
{#                                <input type="text" name="username1" id="checkcode">#}
{#                                <img src="image/verify_code.jpg" id="img_check">#}
{#                            </td>#}
                        </tr>
                        <tr>
                            <td colspan="2" align="center"  >
                                <div id="btn_sub" >註冊</div>
{#                                <input type="submit" value="註冊" id="btn_sub">#}
                            </td>
                        </tr>

                    </table>
                </form>
            </div>
        </div>
        <div class="rg_right">
            <p>已有帳號?<a href="/login">當即登陸</a></p>
        </div>
    </div>
</body>
<script src="/static/js/jquery-3.5.1.min.js"> </script>
<script>
    $("#btn_sub").click(function (){
        var data={}
        data['username']=$("#username").val()
        data['password']=$("#password").val()
        data['email']=$('#email').val()
        data['birthday']=$('#birthday').val()
        data['name']=$('#name').val()
        data['tel']=$('#tel').val()
        data['gender']=$('input:radio[name="gender"]:checked').val();
        $.ajax({
            data:data,
            dataType:"json",
            "type":"POST",
            "url":'/register',
            "success":function (arg){
                if(arg.status=="ok"){
                    window.location.replace("/login")
                }else if(arg.msg=="用戶已存在"){
                    $(".user_err").text(arg.msg)
                }else if(arg.msg=="性別爲必選項"){
                    $(".gender_err").text(arg.msg)
                }else if(arg.msg=="日期爲必選項"){
                    $(".birthday_err").text(arg.msg)
                }
            }
        })
    })
</script>
</html>

register.cssjquery

*{
    margin: 0px;/*全部的外邊距爲0*/
    padding: 0px;/*全部的內邊距爲0*/
    box-sizing: border-box;/*規定兩個並排的帶邊框的框*/
}
body{
    background: url("image/register_bg.png")no-repeat center;
    padding-top: 25px;
}
.rg_layout{
    width: 900px;
    height: 500px;
    border: 8px solid #EEEEEE;/*solid 定義實線*/
    background-color: white;
    margin: auto;
}
.rg_left{
    float: left;
    margin: 15px;
}
.rg_left>p:first-child{
    color: #FFD026;
    font-size: 20px;
}
.rg_left>p:last-child{
    color: #A6A6A6;
    font-size: 20px;
}

.rg_center{
    float: left;
}

.rg_right{
    float: right;
    margin: 15px;
    padding-left: 50px;
}
.rg_right p{
    font-size: 15px;
}
.rg_right p a{
    color: coral;
}
.td_left{
    width: 100px;
    text-align: right;
    height: 45px;
}
.td_right{
    padding-left: 50px;
}
#username,#password,#email,#name,#tel,#birthday,#checkcode{
    width: 251px;
    height: 32px;
    border: 1px solid #A6A6A6;
    /*設置邊框圓角*/
    border-radius: 5px;
    padding-left: 10px;
}
#checkcode{
    width: 110px;
}
#img_check{
    height: 32px;
    vertical-align: middle;/*設置圖片的位置垂直居中*/
}
#btn_sub{
    width: 100px;
    height: 40px;
    text-align: center;
    line-height: 40px;
    background-color: #FFD026;
    border: 1px solid #FFD026;
    padding-left: 10px;
}

<1>.ajax的做用
咱們知道咱們每次對服務器發送請求,服務器處理後都會發給咱們一個頁面,可是有時候咱們兩次發送請求的應該獲得的頁面是大同小異的,好比後臺管理的時候增長一條數據,我只須要在頁面上顯示這條數據便可,其餘關於頁面的排版之類的是不須要動的,這個時候,從新接收一個頁面顯然是不必的,因而ajax就出現了。
ajax就是當你作了某個動做(好比鼠標移動到某個位置)後,偷偷地日後臺發送數據,而後取得數據後偷偷地在前端處理並顯示,因此不難想象ajax是包含在事件處理函數中,須要數據(data),提交的地方(url),收到響應後的處理函數等參數,格式以下:ajax

funtion(){
$.ajax({
data:{"a":1},
dataType:"json", //當服務端返回json字符串,自動把接收的arg轉爲json對象,不加此句,則需obj=json.parse(arg)
"type":"POST",
"url":'/register',
"success":function (arg){
}
})
}
success表明處理成功函數,同理還有其餘的函數
type表示請求方法sql

debug:數據庫

  1. jQuery 取選中的radio的值方法

$('input:radio[name="gender"]:checked').val();django

2.ajax 用get請求能夠匹配url,post報錯
「django.urls.exceptions.NoReverseMatch: Reverse for '<WSGIRequest: POST '/login'>' not found. '<WSGIRequest: POST '/login'>' is not a valid view function or pattern name.」json

在url.py中排除半天,最後發現是views.register裏面引用 redirect方法有誤
錯誤:redirect(request,'login')
正確:redirect('/login')
可見,出現路徑匹配錯誤是也要看看重定向等方法是否有誤

3.ajax data變量有值,可是post數據爲空查了半天,後面發現是由於定義變量時用了[],應該用{}表字典錯誤: var data=[]正確: var data={}

相關文章
相關標籤/搜索