python使用flask模块和前端交互基础

本文介绍了如何使用Python的Flask模块和前端Ajax进行数据交互。通过实例展示了Flask设置跨域支持、创建API接口以及前端使用XMLHttpRequest发送POST请求获取数据的过程。重点讲解了Flask的CORS配置和Ajax请求响应的处理。
摘要由CSDN通过智能技术生成

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.responseText
            var resultJson = JSON.parse(result)
            console.log(resultJson)
          }
        }
      }
    }
  </script>
</body>
</html>

最后

前端获取信息
在这里插入图片描述

前端主要使用的模块是XMLHttpRequest(),使用方法比较简单,所以没有加注释信息,如果有对这块不是太了解的伙伴,可以参考JS中的Ajax发送请求获取数据流程

  • 2
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

讷言丶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值