【问题标题】:Best method for dynamically building URL with Flask url_for使用 Flask url_for 动态构建 URL 的最佳方法
【发布时间】:2017-03-29 16:35:47
【问题描述】:

我必须使用 url_for 在 JavaScript 中创建一个 URL,因为我应该使用整个表格行作为我无法在 HTML 中执行的链接。示例如下:

{% for x in last_orders %}
<tr id="x">
    <td>something here</td>
    <td>something here</td>
</tr>
{% endfor %}

还有烧瓶:

@app.route("/some/page/<int:id>/", methods=['POST', 'GET'])
def xxx_page(id):

我可以使用 Jquery 函数 .click() 使表格行像链接一样,但是使用这种方法我不能以正确的方式使用 url_for。

我在另一个主题中看到我可以使用 Post 发送变量,但我不想更改我的 URL 系统,因为这样对用户更友好。

也许我可以使用 url_for (/some/page/0) 创建虚拟 URL,然后使用 JavaScript 更改该字符串,但我不确定这种方法是否最好。

编辑:我的方法是这样的:

$(".row").click(function() {
    var id = $(this).attr("id");
    var where = `{{ url_for('xxx_page', id=0) }}`;
    where = where.slice(0,-2).concat(id + "/");
    window.location = where;
  });

【问题讨论】:

    标签: python flask url-for


    【解决方案1】:

    如果last_orders 的元素包含xxx_page 函数中使用的前缀,那么您可以在td 中创建一个a 标记。

    <td><a href={{ url_for('{}_page'.format(x)) }}>something here</a></td>
    

    编辑:重读您的问题后,您希望使整个单元格可点击。 JavaScript 中有几个选项。您可以监听对所有td 元素的点击,然后触发对其子a 的点击。

    # Don't actually use an anonymous function. Define it elsewhere.
    $('body').off('click.order')
        .on('click.order', 'td', function(e) {
            $(this).find('a').trigger('click');
        });
    

    或者(我比第一个选项更喜欢这个选项)你可以在 td 元素上设置一个数据元素和地址。

    <td data-url='{{ url_for('{}_page'.format(x)) }}'>something here</td>
    

    然后在您的 click 监听器中,执行此操作。

    window.location.href = $(this).attr('data-url');
    

    【讨论】:

      猜你喜欢
      • 2011-11-20
      • 1970-01-01
      • 1970-01-01
      • 2022-11-12
      • 2015-11-21
      • 1970-01-01
      • 2012-01-07
      • 1970-01-01
      • 2010-10-18
      相关资源
      最近更新 更多