Layui新建一个login.html网页,有用户名和密码两个输入框,一个按钮,当按钮提交后把数据通过ajxa发送给login.py,通过验证后主页转到hello.html,如果验证失败返回,密码错误,前端用layui,后端用flask请写出详细代码和注释
时间: 2024-03-23 11:37:26 浏览: 67
好的,以下是详细代码和注释:
1. login.html
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>登录</title>
<!-- 引入layui样式 -->
<link rel="stylesheet" href="https://cdn.staticfile.org/layui/2.5.6/css/layui.min.css">
</head>
<body>
<!-- 表单 -->
<form class="layui-form" action="" method="post">
<div class="layui-form-item">
<label class="layui-form-label">用户名</label>
<div class="layui-input-block">
<input type="text" name="username" required lay-verify="required" placeholder="请输入用户名" autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">密码</label>
<div class="layui-input-block">
<input type="password" name="password" required lay-verify="required" placeholder="请输入密码" autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<div class="layui-input-block">
<button class="layui-btn" lay-submit lay-filter="login">登录</button>
</div>
</div>
</form>
<!-- 引入layui -->
<script src="https://cdn.staticfile.org/layui/2.5.6/layui.min.js"></script>
<script>
//layui的使用
layui.use(['form', 'layer'], function(){
var form = layui.form;
var layer = layui.layer;
//监听提交
form.on('submit(login)', function(data){
//ajax发送请求
$.ajax({
url: '/login',
type: 'POST',
data: data.field,
success: function(res){
//如果验证成功,跳转到主页
if(res.code === 200){
window.location.href = '/hello';
}else{
//如果验证失败,弹出错误信息
layer.msg(res.msg);
}
}
});
return false;
});
});
</script>
</body>
</html>
```
2. login.py
```python
from flask import Flask, request, jsonify, render_template
app = Flask(__name__)
# 登录页面
@app.route('/')
def login():
return render_template('login.html')
# 登录接口
@app.route('/login', methods=['POST'])
def login_check():
# 接收用户名和密码
username = request.form.get('username')
password = request.form.get('password')
# 验证用户名和密码
if username == 'admin' and password == '123456':
return jsonify({'code': 200, 'msg': '登录成功'})
else:
return jsonify({'code': 400, 'msg': '用户名或密码错误'})
# 主页
@app.route('/hello')
def hello():
return 'Hello, World!'
if __name__ == '__main__':
app.run(debug=True)
```
以上就是使用Layui和Flask实现登录验证功能的详细代码和注释,希望能对你有所帮助。
阅读全文