python利用flask模块和前端进行交互基础
一、模块使用:
python:flask、flask_cors
【两个都是第三方模块需要进行按照】推荐使用豆瓣源安装,以下为豆瓣源安装方法
pip install flask -i https://pypi.douban.com/simple/
pip install flask_cors -i https://pypi.douban.com/simple/
前端: Ajax
二、代码演示
python
from flask import Flask
from flask_cors import CORS #导入解决跨域问题的模块
app = Flask(__name__)CORS(app, supports_credentials=True) #动态解决前端跨域问题
app.debug = True #开启flask调试模式
@app.route('/',methods=['post']) #指定请求路径、方法
def add_stu():student_json = {"name":"jerry","age":15,"class":["math","english","chinese"],"state":True}return student_json
if __name__ == '__main__':app.run(host='localhost',port=1234)#指定端口号和地址
web界面
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>flask模块前端测试界面</title>
</head>
<body><button onclick="fun()">请求数据</button><script>function fun(){console.log('request begin')var xhr = new XMLHttpRequest();xhr.open('post','http://localhost:1234',true);xhr.send(null);xhr.onreadystatechange = async function(){if(xhr.readyState === 4){if(xhr.status === 200){var result = xhr.responseTextvar resultJson = JSON.parse(result)console.log(resultJson)}}}}</script>
</body>
</html>
最后
前端获取信息
前端主要使用的模块是XMLHttpRequest(),使用方法比较简单,所以没有加注释信息,如果有对这块不是太了解的伙伴,可以参考JS中的Ajax发送请求获取数据流程