ajax實現用戶注冊


  需求分析

  • 頁面中給出注冊表單;
  • username input標簽中綁定onblur事件處理函數。
  • 當input標簽失去焦點后獲取 username表單字段的值,向服務端發送AJAX請求
  • django的視圖函數中處理該請求,獲取username值,判斷該用戶在數據庫中是否被注冊,如果被注冊了就返回“該用戶已被注冊”,否則響應“該用戶名可以注冊”。

 

js代碼

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>用戶名是否被注冊</title>
    <script src="/static/jquery-3.3.1.js"></script>
    <style>
        .display {
            display: none;
        }
    </style>
</head>
<body>
<form>
    <input type="text" name="username" onblur="r()" class = 'username'>
    <input type="password" name="password" class="password">
    <span id='msg' class="display"></span>
</form>
{#<button onclick="r()">登錄</button>#}

<script>
        function r(){
            $.ajax({
                url : '/register/',
                data : {
                    'username' : $('.username').val(),
                    'password' : $('.password').val(),
                },
                type : 'POST',
                success: function(data){
                    console.log(data)
                    $('#msg').removeClass('display')
                    $('#msg').text(data)
                }
            })
        }
</script>
</body>
</html>

views.py

def register(request):
    username = request.POST.get('username')
    password = request.POST.get('password')
    print(type(username))
    if username =='123':
        print("!!")
        return HttpResponse('該賬號已注冊')
    else:
        return HttpResponse('ok')

 

urls.py

urlpatterns = [
    path('register/',views.register),
    path('login2/',views.login2)
]

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM