# python后端
from flask import *
import json
app = Flask(__name__)
testInfo = {}
.route('/server', methods=['GET', 'POST']) # 本server将向html发json数据的标准格式
def test_post():
# python接受前端发来的ajax请求,并提取出其中的键cho的值
cho = request.form.get('cho')
testInfo['name'] = '小刘'
testInfo['age'] = '27'
testInfo['cho'] = cho
# 第二个参数为true,会让中文被编码
result = json.dumps(testInfo, ensure_ascii=False)
result = make_response(result)
# 5000端口的网站想让其他端口的网站读取5000端口网站数据,得允许同源策略
result.headers['Access-Control-Allow-Origin'] = '*'
return result # python向前端回应ajax请求
if __name__ == "__main__":
app.run() # 执行本脚本时就启动5000端口(端口5000好像是缺省值),注意,这暗示着你需要运行本脚本,每次修改代码需要重启脚本
<script> // 前端的js区
let xhr = new XMLHttpRequest();
xhr.open('POST', 'http://127.0.0.1:5000/server');
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send("cho=1");
xhr.addEventListener('readystatechange', ()=>{
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
console.log(xhr.response);
}
}
})
</script>

后端接受前端发来的数据
看上面案例的
python后端有一行
# python接受前端发来的ajax请求,并提取出其中的键cho的值
cho = request.form.get('cho')
- THE END -
最后修改:2023年10月16日
非特殊说明,本博所有文章均为博主原创。
共有 0 条评论