jquery ajax 与 flask 传输 json 并且 提取ajax数据作为全局变量

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> <!--引入jquery-->
</head>
<body>
<h1>ajax</h1>

<script>
    function get_data() { 
        let data1; // 设置外层变量
        $.ajax({ // ajax请求
            type: "get", // 请求方式
            url: "http://127.0.0.1:5000/ajax", // 服务器路径
            data: { // 请求数据
                name: 'ajax',
                methods: 'get'
            }, // 上传数据
            dataType: "json", // 上传数据格式
            async: false, // 同步,以便接收数据,而不是promise
            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)
    // console.log("data2:", data2)
</script>
</body>
</html>

flask

#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
@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__,  # 创建app
    static_folder="./",  # 设置静态文件夹路径
    template_folder='./',  # 设置模板路径
    static_url_path=''  # 设置静态文件路径
)

app.secret_key = os.urandom(24)  # 加密密钥混合,生成session标号
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',  # ip
        port=5000,  # 端口
        # ssl_context='adhoc',  # 默认SSL证书,实现https
        threaded=True,  # 多线程
    )
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

夏华东的博客

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

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

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

打赏作者

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

抵扣说明:

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

余额充值