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) ]