首页 > 解决方案 > How can I pass a client-side parameter to a server-side route without using forms?

问题描述

I have a simple Flask web app. My index template has various ways of interacting with clients using javascript and HTML. I am also have a form that, upon submission, routes to another flask process and uses the request.form command to retrieve user-submitted data.

However, I want to do something a little different. I would like to initiate a Flask redirection upon javascript event but include a parameter, and not use form.

For example, my index.html file would display something like this after template rendering:

function startRedirect(parameter) {
    window.location.pathname = '/myRedirect';
}

<input type="checkbox" id="sample" name="sample" onChange="startRedirect(parameter);">

And part of my Flask script would have:

@app.route('/myRedirect')
def myRedirectFunction():
    # do something with the parameter here
    return render_template('index.html')

I realize this can be done with using a form, but I am interested in accomplishing this task without having a form. I was thinking about somehow using request.args, but don't quite understand what to do.

标签: pythonflask

解决方案


您可以使用动态路由来捕获简单的输入并将其传递给路由的函数。

app.route('/myRedirect/<param>')
def myRedirectFunction(param='hello world'):
    return render_template('index.html', param=param)

使用此路由作为重定向,您可以传递一个param(或多个,如果您对它们进行序列化),您可以使用它来做某事。从那里,您可以显示或再次重定向到一个公共端点,这样用户就不会在 url 中看到参数。


推荐阅读