Ajax实现登陆页面设计

Ajax的作用是在不重新加载页面的情况下实现页面的局部刷新。本例子采用的语言是python3,工具为pycharm,服务器为Django,前端使用query-3.2.1.min.js。

1.创建Django项目,创建static静态文件夹存放query-3.2.1.min.js。在setting.py中添加配置:

STATICFILES_DIRS = [os.path.join(BASE_DIR,'static')]

2.前端代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登陆</title>
    <script src="/static/js/jquery-3.2.1.min.js"></script>
    <script>
        $(function () {
            $('#commit').click(function () {
                username = $('#username').val()
                password = $('#password').val()
                $.ajax({
                    url:'/login_check_ajax',
                    type:'post',
                    data:{'username':username,'password':password},
                    dataType:'json',
                    success:function (data) {
                        if (data.res == 0){
                            $('#message').show().html('用户名或密码不正确')
                        } else {
                            location.href='index'
                        }
                    }
                })
            })
        })
    </script>
    <style>
        #message{
            display: none;
            color: red;
        }
    </style>
</head>
<body>
        <div>
            <input type="text" id="username">
        </div>
        <div>
            <input type="password" id="password" id="">
        </div>
        <div id="message"></div>
        <div>
            <input type="button" value="登陆" id="commit">
        </div>
</body>
</html>

3.后台代码:

from django.shortcuts import render,redirect
from django.http.response import JsonResponse

#首页视图函数
def index(request):
    return render(request,'index.html')

#Ajax登陆页面
def login_ajax(request):
    return render(request,'login_ajax.html')

#Ajax请求视图函数
def login_check_ajax(request):
    username = request.POST.get('username')
    password = request.POST.get('password')
    #如果用户名为fucker,密码为123456则返回1,否则但会0
    if username == 'fucker' and password == '123456':
        return JsonResponse({'res':1})
    else:
        return JsonResponse({'res':0})

4.设置urls.py

urlpatterns = [
    path('index',views.index),
    path('login_ajax',views.login_ajax),
    path('login_check_ajax',views.login_check_ajax),
]

5.启动Django服务,打开浏览器,访问http://127.0.0.1:8000/login_ajax

用户名密码输入正确时,直接跳转首页,错误时给出错误提示

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值