基于Ajax的登陆验证
<form> 用户名 <input type="text" id="user"> 密码 <input type="password" id="pwd"> <input type="button" value="submit" class="login_btn"><span class="error"></span> </form> <script> // 登录验证 $(".login_btn").click(function () { $.ajax({ url: "/login/", type: "post", data: { "user": $("#user").val(), "pwd": $("#pwd").val(), }, success: function (data) { console.log(data); // json字符串 console.log(typeof data); var data = JSON.parse(data);// 反序列化 object {} ,数据转换 console.log(data); // object console.log(typeof data); if (data.user) { console.log(key); location.href = "http://www.baidu.com/"; } else { $(".error").html(data.msg).css({"color": "red", "margin-left": "10px"}) } } }) }) </script>
def login(request): print(request.POST) 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 passwor wrong! " import json # 转换成json ,传送数据 return HttpResponse(json.dumps(res))