一、Ajax的登录验证
利用Ajax实现登录验证,效果图如下:,不成功时显示错误,成功跳转到其它页面。
流程为:①在html页面输入用户名,密码,点击login后,通过POST提交到服务器,服务器通过views对应的函数,解析到用户名、密码字段。然后通过ORM匹配数据库数据,如果匹配成功,则返回用户信息,不成功则返回错误信息。返回的信息都是由html下的ajax JS解析,其中利用到了JSON数据传输,因为Python和JS之间数据类型的不同。python的字典在js中为对象。
html代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Ajax</title> <script src="/static/jquery/jquery-3.4.1.js"></script> </head> <body> <h2>Login——Ajax</h2> <form> 用户名<input type="text" id="user"> 密码 <input type="password" id="pwd"> <input type="button" value="login" class="login_btn"><span class="error"></span> </form> <script> $(".login_btn").click(function () { $.ajax({ url:"/test_ajax/", type:"post", data:{ "user":$("#user").val(), "pwd":$("#pwd").val(), }, success:function (data) { console.log(data) $("#ret").val(data) var data = JSON.parse(data) console.log(data) if (data.user){ location.href="http://baidu.com" } else{ $('.error').html(data.msg) } } }) }) </script> </body> </html>
views函数代码:
def test_ajax(request): user = request.POST.get('user') pwd =request.POST.get('pwd') user=User.objects.filter(name=user,pwd=pwd).first() res = {"user":None,'msg':None} if user: res["user"] = user.name else: res["msg"] = "username or password wrong" import json return HttpResponse(json.dumps(res))
二、