Django from scratch (f) (2)

A, Ajax login verification

  Login authentication using the Ajax implementation, the effect is as follows: displays an error when unsuccessful, successful jump to other pages.

  Process as follows: ① to enter a user name in html pages, password, click login, submitted to the server through the POST, server function by views corresponding to resolve the user name, password field. Then by matching ORM database data, if the match is successful, the user information is returned, unsuccessful error message is returned. Are resolved by the information returned in ajax html JS, which use to JSON data transmission, because different types of data between the Python and JS. python dictionary object in the js.

  

  html code:

<!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 the function code:

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

two,

Guess you like

Origin www.cnblogs.com/alex2yang/p/11127741.html