从JavaScript向Flask传递参数

5
当按下按钮时,我在我的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)

我希望在javascript中做类似于"filename.py".alist(FreeSearch,LimitContent)的事情,但这是不可能的...

1个回答

3
从JS代码中,使用GET方法调用URL到您的Flask路由,将参数作为查询参数传递:
/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)

谢谢!我该如何将 /list?freesearch=value1,limit_content=value2 添加到我的 JavaScript 代码中? - Bonbin
据我所知,您想要做的是从JS代码执行GET(或POST,由您决定)到Python Flask应用程序。有关如何从JS执行请求,请参见[此答案](https://dev59.com/lnVC5IYBdhLWcg3wliKe#4033310)。 - Jérôme

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接