1.注册表单–用户名的验证
思路是将当用户名的input标签 失去焦点时,用ajax向服务器发送数据然后得到响应数据,将数据显示在标签内
在这之前,先把数据库的配置做好,这是flask里的内容直接上代码吧
from flask import Flask,render_template,request
from flask_migrate import MigrateCommand,Migrate
from flask_script import Manager
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = \
"mysql+pymysql://root:995994@localhost:3306/ajaxfuxi"
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['DEBUG'] = True
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
db = SQLAlchemy(app)
manage = Manager(app)
migrate = Migrate(app,db)
manage.add_command('db',MigrateCommand)
class Users(db.Model):
id = db.Column(db.Integer,primary_key=True)
uname = db.Column(db.String(30),unique=True)
upwd = db.Column(db.String(30),unique=True)
nickname = db.Column(db.String(30),unique=False)
email = db.Column(db.String(30))
def to_dict(self):
dic = {
'id':self.id,
'uname':self.uname,
'upwd':self.upwd,
'nickname':self.nickname,
'email':self.email
}
return dic
if __name__ == "__main__":
manage.run()
路由代码
@app.route('/02-regin')
def regin():
return render_template('02-regin.html')
@app.route('/02-server')
def server02():
uname = request.args.get('uname')
user = Users.query.filter_by(uname=uname).first()
if user:
return "已存在 "
else:
return "可以使用"
前端代码
<p>
user:<input type="text" id="uname"><span id="uname-tip"></span>
</p>
JS
$(function () {
$("#uname").blur(function () {
var xhr = createXhr()
xhr.open('get','/02-server?uname='+this.value,true)
xhr.onreadystatechange=function () {
if(xhr.readyState==4 && xhr.status==200){
$("#uname-tip").html(xhr.responseText);
}
}
xhr.send(null)
});
});
运行结果,用户名的合法性验证也可以用ajax做(空格的检测…非法字符等等)
2.get/post请求的ajax使用
GET
@app.route('/01-get')
def test():
return render_template('test.html')
@app.route('/01-server')
def server1():
uname = request.args.get('uname','')
return "请求的参数是:"+uname
$(function () {
$("#btn").click(function () {
var xhr = createXhr();
xhr.open('get','/01-server?uname=zhangzhihan',true)
xhr.onreadystatechange=function () {
if(xhr.readyState==4&&xhr.status==200){
$("#DIV").html(xhr.responseText);
}
}
xhr.send(null);
});
});
# HTML:
<a href="/01-server">非AJAX请求</a>
<button id="btn">AJAX</button>
<div id="DIV"></div>
POST
@app.route('/03-post')
def post():
return render_template('03-post.html')
@app.route('/03-server',methods=['POST'])
def server03():
uname = request.form['uname']
age = request.form['age']
return "uname:%s,age=%s" %(uname,age)
$(function () {
$("#btn1").click(function () {
var xhr = createXhr()
xhr.open('post','/03-server',true)
xhr.onreadystatechange=function () {
if(xhr.readyState==4 && xhr.status==200){
$("#show").html(xhr.responseText);
}
}
// 更改Content-Type 的请求消息头的值 application/x-www-form
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.send('uname=zzh&age=22')
});
})
# HTML 代码
<button id="btn1">POST</button>
<div id="show"></div>
2.将数据库中用户信息显示在前端
@app.route('/04-user')
def user04():
return render_template('04-user.html')
@app.route('/04-server')
def users():
users = Users.query.all()
s = ""
for u in users:
s +="%s_%s_%s_%s_%s|" %(u.id,u.uname,u.upwd,u.nickname,u.email)
s = s[0:-1]
return s
$(function () {
$("#btn3").click(function () {
var xhr = createXhr()
xhr.open('get','/04-server',true)
xhr.onreadystatechange=function () {
if(xhr.readyState==4 && xhr.status==200)
{
var res = xhr.responseText
var users = res.split("|")
var html = ""
$.each(users,function (i,object) {
var infos = object.split("_")
html += "<tr>";
html += "<td>" +infos[1]+"</td>"
html += "<td>" +infos[2]+"</td>"
html += "<td>" +infos[3]+"</td>"
html += "<td>" +infos[4]+"</td>"
html +="</tr>";
})
$("#content").html(html)
}
}
xhr.send(null);
});
});
<button id="btn3">显示</button>
<table width="400" border="1">
<tr>
<th>user</th>
<th>passwd</th>
<th>nickname</th>
<th>email</th>
</tr>
<tbody id="content"></tbody>
</table>