完成注册功能
1.js文件: onclick函数return True时才提交表单,return False时不提交表单
function fnRegist() { var oUpass = document.getElementById('upass').value; var oUpass1 = document.getElementById('upass1').value; if (oUpass.value.length < 6 || oUpass1.value.length > 12) { oError.innerHTML = '密码请在6到12位之间'; return false; }else if (oUpass != oUpass1) { document.getElementById("error_box").innerHTML = "两次密码不一致"; return false; } return true; }
2.html文件:
1.<form>中设置 action和method="post"
2.<input> 中设置 name
<form action="{{ url_for('regist') }}" id="lg-form" name="lg-form" method="post"> <div> <label for="username">Username:</label> <input type="text" name="username" autocomplete="off" placeholder="请输入登录用户名"> </div> <div> <label for="username">nickname:</label> <input type="text" name="nickname" autocomplete="off" placeholder="请输入昵称"> </div> <div> <label for="phonenumber">phonenumber:</label> <input type="text" name="phonenumber" autocomplete="off" placeholder="手机号码" > </div> <div> <label for="password">Password:</label> <input type="password" id="upass" name="password" autocomplete="off" placeholder="设置密码" > </div> <div> <label for="password1">Password1:</label> <input type="password" id="upass1" name="password" autocomplete="off" placeholder="确认密码" > </div> <div id="error_box"></div> <button type="submit" id="regist" onclick="fnRegist()">注册</button> </form>
3.主py文件中:
from flask import request, redirect, url_for
@app.route('/regist/', methods=['GET', 'POST’])
@app.route('/regist/',methods=['GET','POST']) def regist(): if request.method=='GET': return render_template('regist.html') else: username = request.form.get('username') password = request.form.get('password') nickname = request.form.get('nickname') phonenumber = request.form.get('phonenumber') user =User.query.filter(User.username==username).first() if user: return 'username existed' else: user=User(username=username,password=password,nickname=nickname,phonenumber=phonenumber) db.session.add(user) #数据库操作 db.session.commit() return redirect(url_for('login'))