【问题标题】:How to receive jsonify variables on .js file from flask如何从烧瓶接收 .js 文件上的 jsonify 变量
【发布时间】:2020-02-23 16:20:51
【问题描述】:

我想将一个字符串从我的 Flask 应用程序发送到一个 .js 文件(不是 HTML 上的脚本)。我知道我需要使用 Ajax 'GET' 类型,但我不确定如何在 .js 文件和 console.log 数据中接收它。

@app.route('/',methods =['GET','POST'])
def index():
    req = json.dumps(request.get_json())

    if request.method == 'POST':
        result = getString(req) #Function outputs a string
        print('Received')
        return jsonify(result)
    else:
        print('Not Received')

    return render_template('index.html')

if __name__ == '__main__':
    app.run()

.js 文件(需要帮助):

$.ajax({
    url: "/",
    type: 'GET',
    data: ???, #What should i put here
    success: function(data) {
        console.log(data);
    }
});

【问题讨论】:

    标签: javascript python json ajax flask


    【解决方案1】:

    请注意,以下 sn-p 暗示如果端点收到 GET 请求,则不会返回任何内容。

    if request.method == 'POST':
        result = getString(req) #Function outputs a string
        print('Received')
        return jsonify(result)
    else:
        # This is what will get called on a GET request
        print('Not Received')
    

    修复该问题后,除非您想提供一些查询参数,否则您根本不需要 ajax 端的 data 字段。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-17
      • 2020-12-25
      • 2021-12-26
      • 2017-04-29
      • 2020-12-21
      • 1970-01-01
      • 2019-01-04
      相关资源
      最近更新 更多