如何使用jQuery和Flask

时间:2015-08-14 20:11:55

标签: jquery python flask

无论出于何种原因,我最难从Flask中的请求对象中获取我关心的数据。我试图给用户一种方法来将他们的微分方程系统保存为在发送GET请求时在服务器端生成的不同类型的文件,我只需要知道他们想要什么样的文件类型。这是发送请求的代码:

$.ajax({
            type: "GET",
            url: '/',
            data: selected_index,
            success: function(response){
                console.log(response);
                downString = response.downloadString;
            }
        });

这是用于选择要生成哪个文件然后将其发送回字典的代码,以便将 downString 设置为该文件:

@app.route("/", methods=['GET','POST'])
def index():
    if request.method=='GET':
        fileType = request.data
        if fileType=='ode':
            return jsonify({'downloadString':'ODE File Here'})
        if fileType=='mathematica':
            return jsonify({'downloadString':'Mathematica File Here'})

但是,request.data是一个空字符串,所以我一直试图解决这个问题很长一段时间,但仍然找不到方法。如何从请求对象中获取该数据?

1 个答案:

答案 0 :(得分:1)

我想在这里发布我的最终代码,以防任何人提出这个问题并且想知道答案。

save.js

$.ajax({
            type: "GET",
            url: '/',
            data: {'selected_index':selected_index},
            success: function(response){
                console.log(response);
                downString = response.downloadString;
            }
        });

app.py

@app.route("/", methods=['GET','POST'])
def index():
    if request.method=='GET':
        if 'selected_index' in request.args:
            fileType = request.args.get('selected_index')
            if fileType=='ode':
                return jsonify({'downloadString':o.getOdeFile()})
            if request.data=='mathml':
                return jsonify({'downloadString':o.getMathML()})
        return render_template('index.html')