ajax检测注册用户信息主体思路
1.在settings.py中配置需要使用的信息
#对static文件进行配置 STATICFILES_DIRS=[ os.path.join(BASE_DIR,'static') ]
2.在url.py中配置注册register和check地址,
from django.conf.urls import url from django.contrib import admin from app01 import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^register/', views.register), url(r'^check/', views.check), ]
3.在models.py中关联数据库
from django.db import models class User(models.Model): name = models.CharField(max_length=20)
4.在views中写对应register和check视图函数
from django.shortcuts import render,HttpResponse from app01 import models from django.http import JsonResponse #注册用户界面 def register(request): return render(request,'register.html') #检测 def check(request): user = request.POST.get('user','') if user == '': return JsonResponse({'status':'0','msg':'用户名为空'}) ret = models.User.objects.filter(name = user) if ret: return JsonResponse({'status':'1','msg':'用户名已存在'}) else: return JsonResponse({'status':'2','msg':'用户名可以使用'})
5.写register.html模板
<html lang="en"> <head> <meta charset="UTF-8"> <title>ajax_reg</title> </head> <body> <p> 用户名 <input type="text" name="user"><span></span> </p><script src="https://cdn.bootcss.com/jquery/3.1.1/jquery.js"></script> <script src="/static/js/ajax_setup.js"></script> <script> {#方式一#} $('[name="user"]').blur(function () { #失去焦点后提交ajax请求,根据数据库信息进行渲染具体span标签内状态msg _this = $(this); $.ajax({ url:'/check/', type:'post', data:{ 'user':$('[name="user"]').val() }, success:function (res) { 找到span标签 _this.next().text(res.msg) } }) })
{# 方式二 箭头函数#} $('[name="user"]').blur(function () { $.ajax({ url:'/check/', type:'post', data:{ 'user':$('[name="user"]').val() }, success:(res)=> { $(this).next().text(res.msg) } }) }).focus(function () { #获取焦点后 span标签内状态信息为空 $(this).next().text('') }) </script> </body> </html>
..