实现用户登陆功能(需要写出前端和服务器端的核心代码)。提示:假设用户名和密码分别为“admin”和“admin123”则认为登陆成功,否则登陆失败,并在页面显示错误提示信息)。要一个很简短的版本
时间: 2024-10-22 18:30:22 浏览: 10
Python 实现用户名和密码登录
前端(HTML + JavaScript,简单示例):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<form id="loginForm">
<input type="text" id="username" placeholder="Username" required>
<input type="password" id="password" placeholder="Password" required>
<button type="submit">Login</button>
<p id="errorMessage"></p>
</form>
<script>
$(document).ready(function(){
$('#loginForm').submit(function(event){
event.preventDefault();
let username = $('#username').val();
let password = $('#password').val();
if(username === 'admin' && password === 'admin123') {
// 登陆成功,可以跳转到其他页面或清除错误消息
document.getElementById('errorMessage').innerText = '';
alert("Login successful!");
} else {
document.getElementById('errorMessage').innerText = "Incorrect credentials!";
}
});
});
</script>
</body>
</html>
```
服务器端(Python Flask 示例,仅处理基本验证,实际生产环境请使用数据库连接):
```python
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/login', methods=['POST'])
def login():
data = request.get_json()
username = data.get('username')
password = data.get('password')
if username == 'admin' and password == 'admin123':
return jsonify({"status": "success", "message": "Login successful"})
else:
return jsonify({"status": "failure", "message": "Invalid credentials"}), 401
if __name__ == '__main__':
app.run(debug=True)
```
阅读全文