後端視圖代碼javascript
from django.views import View from django.http import HttpResponse,JsonResponse from users import models class Verfiy_username(View): def get(self,request,username): count = models.Users.objects.filter(username= username).count() data = { 'username' : username, 'count' : count } return JsonResponse(data)
urls註冊前端
from django.urls import path,re_path from . import views app_name = 'verifications' urlpatterns = [ re_path('verfiy_username/(?P<username>\w{5,20})/',views.Verfiy_username.as_view(),name = 'verfiy_username'), ]
js代碼java
$(function () { var $username = $("#user_name"); //獲取輸入用戶名框標籤 $username.blur(function () { //焦點失去時,調用用戶驗證函數 check_username(); }); function check_username() { var username = $username.val(); if (username === ''){ message.showError('用戶名不能爲空'); return } if (!(/^\w{5,20}$/).test(username)){ message.showError('請輸入5-20個字符的用戶名'); return } //發送AJAX請求,查詢用戶名是否已被註冊 $.ajax({ type: "GET", url: '/verfiy_username/' + username + '/', //url不要使用雙引號,有bug // url: '/usernames/' + username + '/', dataType: 'json' }) .done(function (data) { if (data.count == 0) { message.showInfo(data.username + '能正常使用'); // alert("能正常使用"); } else { message.showError(data.username + '用戶已被註冊過'); } }) .fail(function () { message.showError("服務器超時,請從新刷新一遍"); }); } });