将参数从javascript传递到flask
问题内容:
当按下按钮时,我在html文件中调用了一个javascript函数,该函数将两个字符串作为参数(来自输入字段)。调用该函数时,我想将这些参数传递给我的flask文件并在那里调用另一个函数。我将如何做到这一点?
JavaScript:
<script>
function ToPython(FreeSearch,LimitContent)
{
alert(FreeSearch);
alert(LimitContent);
}
</script>
我要调用的flask函数:
@app.route('/list')
def alist(FreeSearch,LimitContent):
new = FreeSearch+LimitContent;
return render_template('list.html', title="Projects - " + page_name, new = new)
我想做类似"filename.py".alist(FreeSearch,LimitContent)
javascript的操作,但不可能…
问题答案:
从JS代码中,调用(使用GET方法)URL到烧瓶路径,并将参数作为查询args传递:
/list?freesearch=value1&limit_content=value2
然后在您的函数定义中:
@app.route('/list')
def alist():
freesearch = request.args.get('freesearch')
limitcontent = request.args.get('limit_content')
new = freesearch + limitcontent
return render_template('list.html', title="Projects - "+page_name, new=new)
另外,您可以使用路径变量:
/list/value1/value2
和
@app.route('/list/<freesearch>/<limit_content>')
def alist():
new = free_search + limit_content
return render_template('list.html', title="Projects - "+page_name, new=new)