Ajax

异步的javascript
在不全部加载某一个页面部的情况下 对页面进行局的刷新
ajax请求都在后台

登录案例

访问登录页面 页面显示登录窗口
页面内嵌ajax将输入在页面的信息传递给检测视图
视图收到的不管是html传递的还是ajax传递的都使用request.POST或GET接收
检测视图检查输入是否正确返回对应的json给ajax
检测视图只返回json而不重定向 如果重定向 将只在ajax后台显示
当输入正确 ajax 重定向到成功登录后的页面
当输入错误 ajax 提示错误信息而不刷新页面
ajax是异步执行的 JS在执行到ajax时并不会等待ajax的阻塞
HTML内容:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ajax登陆页面</title>
    <script src="/static/js/jquery-1.12.4.min.js"></script>
    <script>
        $(function(){
            //绑定btnAjax 的click 事件
            $("#btnAjax").click(function(){
                login_name=$("#username").val()
                login_passwd=$("#userpasswd").val()
                $.ajax({
                    "url":"ajax_handle",
                    "type":"post",
                    "data":{
                        "name":login_name,
                        "passwd":login_passwd
                        },
                    "dataType":"json"
                }).success(function(data){
                    //进行处理
                    if (data.res == 0){
                        $("#errmsg").show().html("用户名或密码错误")
                    }
                    else{
                        location.href = "/"
                    }
                })
            })
        })
    </script>
    <style>
        #errmsg{
            display: none;
            color: red;
        }
    </style>
</head>
<div>
    <label>登陆<input type="text" id="username"></label><br />
    <label>密码<input type="password" id="userpasswd"></label><br />
    <input type="button" id="btnAjax" value="登陆">
    <div id ="errmsg"></div>
</div>
</html>

视图函数内容:

def ajax_login(request):
    return render(request, "book/test_ajax.html")


def ajax_handle(request):
    u_name = request.POST.get("name")
    u_password = request.POST.get("passwd")
    try:
        if Login.objects.get(name=u_name) and Login.objects.get(password=u_password):
            return JsonResponse({"res": 1})
    except Login.DoesNotExist:
        return JsonResponse({"res": 0})

推荐阅读更多精彩内容