Flask:如何将JSON传递给javascript文件? [重复]

问题描述 投票:0回答:2

我有对象main.py

from __future__ import with_statement
from flask import Flask,request,jsonify,send_file,render_template
import json
# from flask_cors import CORS

app = Flask(__name__, static_url_path='/vendor')
# CORS(app)


@app.route('/')
def home():
    return render_template('index.html',id_user="id1")


@app.route('/receive_word',methods=['POST'])
def receive_word():
    print(request.form)
    data = request.form['javascript_data']
    d = json.loads(data)
    print(d['key1'])
    print(d['key2'])
    return d

我有麦克风.js

$.post("/receive_word", {
    javascript_data: JSON.stringify({ "key1":1, "key2":this.currentTranscript })
});
console.log({{ d }});

如何将main.py中的d传递给main.js?代码无法从main.py中捕获到d变量。谢谢

javascript python html flask
2个回答
1
投票

您似乎使用JQuery来调用您的端点。您应该使用$.post回调参数:

$.post("/receive_word", {
    javascript_data: JSON.stringify({ "key1":1, "key2":this.currentTranscript })
}, 
// Here is the callback
function(d, status){
     // process d
});

0
投票

使用jsonify在Flask视图中返回json数据,假设d是一个有效的Python dict:

@app.route('/receive_word',methods=['POST'])
def receive_word():
    data = request.form['javascript_data']
    d = json.loads(data)   
    return jsonify(d)
© www.soinside.com 2019 - 2024. All rights reserved.