如何将变量从 html 传递到后端烧瓶 [英] how to pass variable from html to backend flask

查看:26
本文介绍了如何将变量从 html 传递到后端烧瓶的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有很多带有标签的 td 元素,我想知道用户点击了哪个元素,我想从 html 传递到后端并在后端处理用户的选择;

there is so many td element with a tag and i want to know that user clicked which element and i want to pass from html to backend and process with user's selection on backend ;

这是我的 html ;

this is my html ;

<a href="/selected" ????><td>{{ options1 }}</td></a>
<a href="/selected"><td>{{ options2 }}</td></a>
<a href="/selected"><td>{{ options3 }}</td></a>
<a href="/selected"><td>{{ options4 }}</td></a>
<a href="/selected"><td>{{ options5 }}</td></a>
<a href="/selected"><td>{{ options6 }}</td></a>

当用户点击一个时,我想把它发送到后端;

when user clicked one , i want to send it to backend ;

@app.route('/selected', methods=['GET', 'POST'])
def selected():
selected_option = request.args.get('????')
return render_template("selected.html", selected_option=selected_option)

如何填问号?

推荐答案

options1options2 等设置单独的变量可能会使这变得很麻烦,原因有几个:

Having the separate variables for options1, options2, etc probably makes this a hassle for a few reasons:

  • 您需要手动更新模板的硬编码以添加更多选项.
  • 每个选项的 URL 部分可能与链接文本不同.

您可能希望在字典中定义您的选项:

You may wish to define your options in a dictionary:

sections = {'first-option': 'I am the first option',
            'second-option': 'Click me for fun and profit',
            'third-option': 'All flights have been cancelled',
           }

现在在生成链接栏的页面上,如果您传递它:

Now on the page which generates your link bar, if you pass that across:

return render_template('some_page.html', SECTIONS=sections)

然后您可以执行以下操作:

You can then do something like:

{% for key, value in SECTIONS.items() %}
  <a href="{{url_for('selected', section=key)}}">{{value}}</a>
{% endfor %}

这将自动生成正确的网址,与以下视图功能兼容:

This will automatically generate the correct URLs, which are compatible with the following view function:

@app.route('/selected/<section>')
def selected(section):
    # Assuming the first URL:
    print (section) # 'first-option'
    print (sections[section]) # 'I am the first option'

    return render_template("selected.html", selected_option=section)

您可能还想看看这个要点进一步.

You may also wish to have a look at this gist which takes the concept a bit further.

这也使用上下文处理器将该 SECTIONS 变量插入到所有页面中,而不是将其传递给各个 render_template 函数.

This also uses a context processor to insert that SECTIONS variable into all pages, rather than passing it to the individual render_template functions.

这篇关于如何将变量从 html 传递到后端烧瓶的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆