python+flask+ajax 注册实例
2019-05-04 本文已影响0人
灰太狼256
先上效果图:
文件名称为register.html
前端代码只做为参考,像flex布局,rem适配,js部分等,就自行学习吧 ^ ^
jquery用的是百度的地址(访问速度快):
http://libs.baidu.com/jquery/2.1.4/jquery.min.js,
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<title>register</title>
</head>
<style type="text/css">
body{
font-size: 16px;
text-align: center;
}
input{
height: 35px;
width: 90%;
border:1px solid #999999;
border-radius: 2px;
text-indent: 10px;
}
.hint{
text-align: left;
padding-left: 5%;
color: #F95E5A;
font-size: 12px;
}
.button{
color: #fff;
height: 40px;
line-height: 40px;
width: 90%;
margin: 0 auto;
text-align: center;
background: #0079fe;
border-radius: 2px;
}
.button:active{
background: #3399ff;
}
.margin-top-30{
margin-top: 30px;
}
.margin-top-100{
margin-top: 100px;
}
</style>
<body>
<h1 class="margin-top-100">Register</h1>
<div class="input margin-top-30">
<input id="username" type="text" placeholder="username">
</div>
<div class="input margin-top-30">
<input id="password" type="password" placeholder="password">
</div>
<div id="hint" class="hint margin-top-30"> </div>
<div onclick="register()" class="margin-top-30 button">register</div>
</body>
<script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript">
function register() {
var usernameValue = document.getElementById('username').value;
var passwordValue = document.getElementById('password').value;
var hint = document.getElementById('hint');
if (usernameValue == '') {
hint.innerText = '提示:请输入用户名';
return;
}else if (passwordValue == '') {
hint.innerText = '提示:请输入密码';
return;
}else{
$.ajax({
type: 'POST',
url: 'http://localhost:5000/',
data: JSON.stringify({
"username": usernameValue,
"password": passwordValue
}),
dataType: 'json',
success: function(ret) {
alert(ret)
},
error: function(err) {
}
})
}
}
</script>
</html>
python代码,命名为register.py
:
from flask import Flask, render_template, request, jsonify
import json
app = Flask(__name__)
@app.route('/',methods=["GET", "POST"])
def hello():
if request.method == 'GET':
print(request.method)
return render_template('register.html')
else:
print(request.method)
data = json.loads(request.get_data(as_text=True))
print(data)
return '200'
if __name__ == '__main__':
app.run(debug=True)
1.命令行输入,运行register.py
文件:
>>> python register.py
2.在浏览器里打开register.html
,输入用户名和密码:
点击提交你会在页面看到返回
200
,命令窗口会输出前端传来用户名和密码:关于json模块与flask jsonify拓展包使用请参考:
https://www.jianshu.com/p/2e3da6d5ad6c