jquery ajax 与 flask 传输 json 并且 提取ajax数据作为全局变量
jquery
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Title</title>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<h1>ajax</h1>
<script>
function get_data() {
let data1;
$.ajax({
type: "get",
url: "http://127.0.0.1:5000/ajax",
data: {
name: 'ajax',
methods: 'get'
},
dataType: "json",
async: false,
success: function (res) {
console.debug("响应数据", res);
data1 = res;
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.error("请求失败!");
}
});
console.debug("data1:", data1)
return data1
};
const response = get_data()
console.debug("response:", response)
</script>
</body>
</html>
flask
"""
@Introduce : 实现一个简单的登录逻辑处理
@File : .py
@Time : 2021-02-18 17:19
@Author : xia hua dong
@Tel : 173 179 76823
@Eamil : 17317976823@163.com
@pip : pip install flask
pip install flask_cors
pip install pyOpenSSL
"""
from flask import Flask, jsonify, render_template, request, session, make_response, flash
from flask_cors import CORS
import os
app = Flask(
__name__,
static_folder="./",
template_folder='./',
static_url_path=''
)
app.secret_key = os.urandom(24)
CORS(app, supports_credentials=True)
@app.route('/ajax', methods=['GET', 'POST'])
def ajax1():
dic = request.values.to_dict()
print('get请求数据:', dic)
return {
'name': 'flask',
'methods': 'get'
}
if __name__ == "__main__":
app.run(
debug=True,
host='0.0.0.0',
port=5000,
threaded=True,
)