Flaskr url_for with parameters not working when called from javascript to python

时光总嘲笑我的痴心妄想 提交于 2021-01-04 15:55:11

问题


I am in the middle of creation of a web application.

In javascript, I make a ajax call to my python script, process and send the result back as response. /process/ is the route to the python script for the processing of values which are sent as json, namely value1 and value2. I send back response as json setting value in key 'result'.

In the success block of ajax, the value is stored in name_value and this should be passed as parameter to the python routing method.

Javascript:

$.ajax({
        type: "GET",
        url: "/process/",
        contentType: "application/json; charset=utf-8",
        data: { "value1" : value1,
                "value2" : value2
               },
        success: function(data) {
            var name = data.result;
            console.log(name);
            window.location.href = "{{url_for('/process2', name=name)}}"
        }
    });

Python script:

app.route("/process2/<name>")
def process2(name):
    print name
    render_template("user.html", name=name);

I am not receiving the parameter value in this case if parameter is passed in url_for. If I hardcode the parameter, I am able to receive the parameter value in the python script as in,

window.location.href = "{{url_for('/process2', name='helloworld')}}"

Any help is appreciated. Thanks in advance.


回答1:


From experience, I have learned that Jinja cannot utilize Javascript variables, like the following:

window.location.href = "{{ url_for('/process2', name=name) }}"

If I am wrong about that, somebody please correct me and you shall become my best friend in the SO community.

EDIT:

As Jason Heine mentioned, you can achieve what you want by passing in the url_for method as the result in the json:

Python:

from flask import jsonify, url_for

@app.route("/process", methods=['GET', 'POST'])
def process():    
    name = 'bubba'  # code to get the name
    return jsonify({
        'result': url_for('process2', name=name),
        'name': name
     })

@app.route("/process2/<string:name>")
def process2(name):
    print name
    render_template("user.html", name=name);

Javascript:

$.ajax({
    type: "GET",
    url: "/process",
    contentType: "application/json; charset=utf-8",
    data: { "value1" : value1,
            "value2" : value2
           },
    success: function(data) {
        var route = data.result;
        var name = data.name;
        console.log(route, name);

        window.location.href = route;
    }
});

You may also check out the AJAX with jQuery documention if you have any more questions.



来源:https://stackoverflow.com/questions/27114227/flaskr-url-for-with-parameters-not-working-when-called-from-javascript-to-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!