从JavaScript调用python的Flaskr url_for参数不起作用 [英] Flaskr url_for with parameters not working when called from javascript to python
问题描述
我正在创建Web应用程序.
I am in the middle of creation of a web application.
在javascript中,我对python脚本进行了ajax调用,处理并将结果作为响应发送回去. /process/是到python脚本的路由,用于处理作为json发送的值(即value1和value2).我在密钥结果"中将响应作为json设置值发送回去.
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'.
在ajax的成功块中,该值存储在name_value中,并且应将其作为参数传递给python路由方法.
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:
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脚本:
app.route("/process2/<name>")
def process2(name):
print name
render_template("user.html", name=name);
在参数url_for中传递参数的情况下,我没有收到参数值.如果我对参数进行硬编码,则可以像在python脚本中那样接收参数值,
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.
推荐答案
根据经验,我了解到Jinja无法利用Javascript变量,如下所示:
From experience, I have learned that Jinja cannot utilize Javascript variables, like the following:
window.location.href = "{{ url_for('/process2', name=name) }}"
如果我对此有误,请有人纠正我,您将成为SO社区中我最好的朋友.
If I am wrong about that, somebody please correct me and you shall become my best friend in the SO community.
正如Jason Heine所提到的,您可以通过将url_for
方法作为json的结果传入来实现所需的目标:
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:
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;
}
});
您也可以查看带有jQuery的AJAX 文档,如果您有还有其他问题.
You may also check out the AJAX with jQuery documention if you have any more questions.
这篇关于从JavaScript调用python的Flaskr url_for参数不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!