【问题标题】:Django dynamic URL dispatcher within javascriptjavascript 中的 Django 动态 URL 调度程序
【发布时间】:2021-07-09 13:26:54
【问题描述】:

我正在尝试使用动态 url 调度程序,例如:

"{% url 'url_name' 'variable' %}" variable 在我的 javascript 中动态设置。

我想要做的基本上是在 <select> 值更改时重定向到不同的页面。

$(document).ready(function() {
  $('#select').change(function() {
      var id = $('#select').val();
      window.location.replace("{% url 'url_name' 'id' %}");
  });
});

我不能像这样使用简单的字符串 concat 来做到这一点: "{% url 'url_name' '" + id + "' %}" 因为它返回此错误 Reverse for 'url_name' with arguments '('" + id + "',)' not found.

选择本身正在填充后端数据:

<select id="select">
  {% for item in list %}
  <option value="{{item.id}}">{{item.name}}</option>
  {% endfor %}
</select>

我不知道这是什么语法。

【问题讨论】:

    标签: javascript django django-templates


    【解决方案1】:

    问题是 js 在浏览器中运行而 django 在服务器上运行,因此您无法使用在不同环境和不同时间运行的两种语言来解析该表达式

    您可以在每个&lt;option&gt; 上使用data- 属性来打印网址

    <select id="select">
      {% for item in list %}
      <option data-url="{% url 'url_name' item.id %}" value="{{item.id}}">{{item.name}}</option>
      {% endfor %}
    </select>
    

    JS

    $('#select').change(function() {
      var url = $(this).find('option:selected').data('url');
      window.location.replace(url);
    });
    

    【讨论】:

      猜你喜欢
      • 2012-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-28
      • 2017-10-31
      • 2020-06-07
      相关资源
      最近更新 更多