python - 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.
解决方案
您可以使用动态路由来捕获简单的输入并将其传递给路由的函数。
app.route('/myRedirect/<param>')
def myRedirectFunction(param='hello world'):
return render_template('index.html', param=param)
使用此路由作为重定向,您可以传递一个param
(或多个,如果您对它们进行序列化),您可以使用它来做某事。从那里,您可以显示或再次重定向到一个公共端点,这样用户就不会在 url 中看到参数。
推荐阅读
- google-sheets - 谷歌表格将 if 语句转换为数组公式
- sql - 根据年龄将人们分为不同的类别
- react-native - 反应原生 Firebase 分析购买事件项目数量始终设置为 0 - 在调试视图中跟踪事件
- ios - UITableView RegisterNib 函数被调用,但是 awakeFromNib 函数从未被调用
- ruby-on-rails - 使用安全电子表格在 xlsx 中添加密码
- kendo-react-ui - 使用 Kend React Grid 的父子折叠
- javascript - Javascript将数组中所有对象的整数属性转换为字符串属性
- floating-point - 整数和浮点数的最佳文字表示
- flutter - Flutter - 返回 UploadTask 而是返回 TaskSnapshot
- git - 如何在非主分支上使用 Firebase 预览托管?