摘要:主要介绍Flask+Ajax前后台数据交互的使用,系统并不完善
代码
app.py
from flask import Flask,render_template,request
import pymysql
import json
app = Flask(__name__)
#设置启动页
@app.route('/')
def begin():
return render_template('index.html')
#设置前台访问的url,以及向前台返回的数据 返回的数据应为json格式
@app.route('/getAll',methods=['POST','GET'])
def getAll():
print("测试")
#print(request.form)
#request.args.get('psw') 获取地址栏(url)中参数,post的参数未通过地址栏,而是通过form传递时,无法获取。
#request.form['username'] 获取Ajax通过POST传过来的值
# username = request.form['username']
# password = request.form['password']
# print(username)
try:
db = getDb()
cur = db.cursor()
sql = "select * from user"
num=cur.execute(sql) # 执行sql语句
print(num)
results = cur.fetchall() # 获取查询的所有记录
jsonData = []
for row in results:
result = {}
result['id'] = row[0]
result['username'] = row[1]
result['password'] = row[2]
jsonData.append(result)
# db.commit()
return json.dumps(jsonData)
except Exception as e:
print("查询数据失败:", e)
finally:
cur.close()
db.close()
def getDb():
try:
db = pymysql.connect(host="127.0.0.1", user="root", password="123456", db="student_mis", port=3306)
return db
except Exception as e:
print("连接数据库失败:", e)
if __name__ == '__main__':
app.run(debug=True)
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
<!-- <link rel="stylesheet" href="bootstrap/bootstrap.min.css">-->
<script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="show"></div>
</body>
<script>
//alert('测试');
$(function () {
$.ajax({
url : '/getAll',
async : false,
type : 'POST',
//data:{"username":"hahaha","psw":"123"},
cache:false,//是否缓存
success : function(data) {
//alert(JSON.stringify(data));
var text="<table class='table table-striped'><thead><tr>" +
"<th>用户名</th><th>密码</th><th>操作1</th><th>操作2</th></tr></thead><tbody>";
for(i=0;i<data.length;i++)
{
/* var sta="";
if(data[i].status==1)
sta="运行中";
else
sta="停止运行"; */
text+="<tr>";
text+="<td>"+data[i].username+"</td>" +
"<td>"+data[i].password+"</td>" +
"<td><button class='btn btn-warning' onclick='update(this.value)' value='"+data[i].id+"'>修改</button></td>" +
"<td><button class='btn btn-danger' onclick='del(this.value)' value='"+data[i].id+"'>删除</button></td>" +
"</tr>";
}
text+="<tbody></table>";
$(".show").html(text);
},
error:function (e) {
alert("出错了!");
},
dataType : "json"
});
})
</script>
</html>