flask之ajax的使用

Ajax 是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术。

一.mysql提取数值形式设置:

1
2
3
4
#连接数据库
self.con=MySQLdb.connect('localhost','root','','demo2',charset='utf8')
#是提取出来的数据以字典的形式出现DictCursor
self.cur=self.con.cursor(cursorclass=MySQLdb.cursors.DictCursor)

二.数据的查询并返回

三.HTML中ajax部分

1.get形式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
var data={
'name':'诺铖'
}
$.ajax({
type:'GET',
async:true,
url:{{url_for("home.ajax")}},
data:data,
contentType:'application/json;charset=UTF-8',
dataType:'json',
success:function(data){
alert(data)
},
error:function(){
alert("失败");
}
});

2.post形式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var data={
'name':'诺铖'
}
$.ajax({
type:'post',
url:'{{url_for("home.ajaxs")}}',
data:data,
dataType:'json',
success:function(data){
data=JSON.stringify(data);
alert(data)
},
error:function(){
alert("失败");
}
})

四.view部分

1
2
3
@home.route('/login',methods=['POST','GET'])
def index():
return render_template("home/login_and_search.html")

1.get请求:

1
2
3
4
5
6
7
8
9
@home.route('/ajax',methods=['POST','GET'])
def ajax():
name=request.args.get('name')
data=[{
'age':18,
'sex':'男'
}]
return jsonify(data)

2.post请求:

1
2
3
4
5
6
7
8
9
@home.route('/ajax',methods=['POST','GET'])
def ajax():
name=request.form.get('name')
data=[{
'age':18,
'sex':'男'
}]
return jsonify(data)

实例1:登录的过程中查找是否有此人,以及在搜索的过程中,查找信息

HTML文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
<!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">
<script src="{{url_for('static',filename='js/jquery-3.3.1.js')}}"></script>
<script src="{{url_for('static',filename='js/jquery-3.3.1.min.js')}}"></script>
</head>
<body>
<script type="text/javascript">
$(function(){
$("#name").blur(function(){
var name=$(this).val();
var data={
'name': name
}
$.ajax({
type:'post',
url:'{{url_for("home.ajaxs")}}',
data:data,
dataType:'json',
success:function(data){
data=eval(data);
console.log(data);
if(data.length==0){
$("#warming").css("color","red");
$("#warming").html("不存在此人");
}else{
$("#warming").css("color","green");
$("#warming").html("欢迎");
}
}
})
})
})
</script>
<div class="form-group" style="margin:100px auto;width:500px;">
<label for="name">名称</label>
<input type="text" class="form-control" id="name"
placeholder="查找是否有此人" ><span id="warming" style="font-size:15px;"></span>
</div>
<div>
<form class="form-horizontal" role="form" style="margin:70px auto;width:500px;">
<div class="form-group">
<label for="firstname" class="col-sm-2 control-label">名字</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="firstname"
placeholder="输入查找" style="position:relative;width:350px;" onkeyup="searchFn(this)" value="">
<div id="searchDiv" style="z-index:2;display:none;border:1px solid;border-color:#bdb9b9;width:350px;position:absolut;">
</div>
</div>
</div>
</form>
<script type="text/javascript">
function searchFn(obj){
var searchWord=document.getElementById("firstname");
var word=searchWord.value;
var data={
'newname':word
};
$.ajax({
type:'POST',
async:true,
url:'{{url_for("home.search_word")}}',
data:data,
dataType:'json',
success:function(data){
data=eval(data);
console.log(data);
var content="";
if(data.length>0){
$("#searchDiv").css("display","block");
for(var i=0;i<data.length;i++){
content+="<div style='padding:5px;cursor:pointer;background:#fff;' onclick='clickFn(this)' onmouseover='mouse_over(this)' onmouseout='mouse_out(this)'>"+data[i].newname+"</div>";
}
$("#searchDiv").html(content);
}
},
error:function(){
alert("失败");
}
})
}
function clickFn(obj){
$("#firstname").val($(obj).html());
$("#searchDiv").css("display","none");
}
function mouse_out(obj){
$(obj).css("background","#fff");
}
function mouse_over(obj){
$(obj).css("background","#337ab7a6");
}
</script>
</div>
</body>
</html>

form.py文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
from flask import request
from flask import render_template
from flask import redirect
from flask import session
import MySQLdb
class Formation():
def __init__(self):
self.con=MySQLdb.connect('localhost','root','','demo2',charset='utf8')
self.cur=self.con.cursor(cursorclass=MySQLdb.cursors.DictCursor)
def isExisted(self,name):
sql="select * from loginusern where username='{}'".format(name)
self.cur.execute(sql)
result=self.cur.fetchall()
return result
def searchAll(self,word):
sql="select newname from news where newname like '%{}%'".format(word)
self.cur.execute(sql)
results=self.cur.fetchall()
return results

view.py文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
from . import home
from flask import request, json
from flask import render_template
from flask import redirect
from flask import session
from flask import url_for
from flask import jsonify
from app.home.forms import *
@home.route('/login',methods=['POST','GET'])
def index():
return render_template("home/login_and_search.html")
@home.route('/ajax',methods=['POST','GET'])
def ajax():
name=request.args.get('name')
f=Formation()
result=f.isExisted(name)
print(result)
print(len(result))
results=jsonify(result)
print(results)
return results
@home.route('/ajax2',methods=['POST','GET'])
def ajaxs():
name=request.form.get('name')
print(name)
f=Formation()
result=f.isExisted(name)
print(result)
print(len(result))
results=jsonify(result)
print(results)
return results
@home.route('/admin',methods=['POST','GET'])
def search_word():
word=request.form.get('newname')
print(word)
f = Formation()
results=f.searchAll(word)
print(results)
result=jsonify(results)
return result

知识点整理:

将字符串转化成json类型使用eval()函数

将光标fellcatch到的数据转化成字典类型光标
self.cur=self.con.cursor(cursorclass=MySQLdb.cursor.DictCursor)

jQuery中ajax之get使用
$.ajax({
type:’GET’,
url:路由,
data:字典类型的数据,
async:false,默认是false,表示异步请求,true是同步
contentType:’application/json;charset=UTF-8’,
dataType:’json’,
success:function(data){data=eval(data)},
error:function(){}

})

jQuery中ajax之post使用
$.ajax({
type:’POST’,
url:路由,
data:字典类型的数据,
async:false,
dataType:’json’,
success:function(data){data=eval(data)},
error:function(){}
})

js事件:onkeyup键盘抬起事件 onclick鼠标点击事件 onmouseout鼠标移开事件 onmouseover鼠标移入事件
后台返回的字典数据进行jsonify()包装。并将其返回前台

Fork me on GitHub