index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="{{url_for('static',filename='jquery.js')}}"></script>
<style>
.my_table {
width: 60%;
}
</style>
<style>
#mask {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, .3);
color: #fff;
font-size: 30px;
text-align: center;
padding-top: 300px;
display: none;
}
</style>
<script>
function setCookie(name, value) {
let Days = 30;
let exp = new Date();
exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
document.cookie = name + '=' + escape(value) + ';expires=' + exp.toGMTString();
}
//get
$(function () {
setCookie('c_mon', 'yyyyyyyyyyyyy')
$('.btn_get').click(function () {
//发送ajax
// $.get(); //get请求
// $.post(); //post请求
$.ajax({
url: '/ajax_req_get',
method: 'get',
data: {
id: 10010,
name: '邓紫棋'
},
headers: { //向请求头加参数
token: 'aghrntndfgsfsdb,gssregege,fsbsbs'
},
beforeSend: function (req) { //类似headers,向请求头加参数
req.setRequestHeader('token2', 'fageshsg,rhdsefasc,nmyuytfhdg')
},
success: function (d) {
console.log(d)
console.log('???')
}
})
})
})
//post
$(function () {
$('.btn_post').click(function () {
$('#my_body').remove();
$('#mask').css('display', 'block');
let tbody = $('<tbody id="my_body"></tbody>') //把html标签变成jquery对象
$.ajax({
url: '/ajax_req_post',
method: 'post',
data: JSON.stringify({ //相当于dumps
id: 10010,
name: '刘亦菲'
}),
headers: { //向请求头加参数
'Content-Type': 'application/json;charset=utf-8'
},
dataType: 'text',
success: function (d) {
console.log(JSON.parse(d)) //loads
console.log('???')
let data = JSON.parse(d)
data.forEach(function (item) { //.forEach 目标必须可迭代
// console.log(item)
let tr = `<tr><td>${item.id}</td><td>${item.name}</td></tr>`
tbody.append(tr);
});
// 把tbody加入table中
$('.my_table').append(tbody);
$('#mask').css('display', 'none');
}
})
})
})
</script>
</head>
<body>
hello {{name}}
<input type="button" class="btn_get" value="点击get">
<input type="button" class="btn_post" value="点击post">
<table class="my_table" border="1">
<thead>
<tr>
<th>id</th>
<th>name</th>
</tr>
</thead>
</table>
<div id="mask"><span>加载中...</span></div>
</body>
</html>
.py
import json
import time
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/')
def func1():
name = 'fox'
return render_template('index.html', name=name)
@app.route('/ajax_req_get')
def ajax_req():
id = request.args.get('id')
name = request.args.get('name')
if not all([id, name]):
return '缺少参数'
return 'hello fox!!!'
@app.route('/ajax_req_post', methods=['POST'])
def ajax_req2():
data = request.json
time.sleep(2)
print(data)
lst = [
{'id': 1, 'name': '鸣人'},
{'id': 2, 'name': '佐助'},
{'id': 3, 'name': '小樱'}
]
# json.dumps(lst, ensure_ascii=False) # 原样输出中文
data = json.dumps(lst)
return data
if __name__ == '__main__':
app.run()