下面是一个 ajax 检测用户名是否可用的例子。
django 项目中。
—— views.py 里—— from django.shortcuts import render,HttpResponse from django.views.decorators.csrf import ensure_csrf_cookie from app01 import models from django.http import JsonResponse @ensure_csrf_cookie def reg(request): # 注册 return render(request,'reg.html') def check(request): # 检测用户名是否可用 user = request.POST.get('user') ret = models.User.objects.filter(name=user) if ret: return JsonResponse({'status':1,'msg':'用户名已存在'}) else: return JsonResponse({'status':0,'msg':'可用的用户名'})
—— reg.html 里—— <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>reg</title> </head> <body> <p>用户名 <input type="text" name="user"><span></span></p> <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script> <script src="/static/js/ajax_setup.js"></script> <script> $('[name="user"]').blur(function () { _this = $(this); {#alert($('[name = "user"]').val());#} $.ajax({ url: '/check/', type: 'post', data: { user: $('[name="user"]').val(), {#属性选择器#} }, success: function (res) { _this.next().text(res.msg) } }) }).focus(function () { _this.next().text('') }); {#链式操作#} </script> </body> </html>
另一种Js 代码:
<script>
$('[name="user"]').blur(function () {
$.ajax({
url: '/check/',
type: 'post',
data: {'user': $('[name="user"]').val()},
success: (res) => { #箭头的使用
$(this).next().text(res.msg)
}
})
}).focus(function () {
$(this).next().text('')
})
</script>
其他:
-- models.py -- from django.db import models class User(models.Model): name = models.CharField(max_length=22) # varchar -------------------------------------------
-- urls.py -- from django.conf.urls import url from django.contrib import admin from app01 import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^reg/', views.reg), url(r'^check/', views.check),] -------------------------------------------
-- settings.py --
STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR,'static')]