【问题标题】:How to make an Ajax call through jquery with dynamic DOM elements in Django templates?如何使用 Django 模板中的动态 DOM 元素通过 jquery 进行 Ajax 调用?
【发布时间】:2016-05-11 19:43:50
【问题描述】:

我有一个侧边栏,其中包含用户最喜欢的商店列表。我希望能够单击商店元素(例如商店、地址)并能够提取有关该元素的信息(例如商店销售)并更新名为“txn_table”的销售表。

我在猜测我必须将商店 ID 传递给 jquery -> Ajax 以获取有关商店的信息,然后更新 DOM。

问题是不同的用户在他们的列表中可能有不同的商店,所以我不能为每个列表元素预先分配 id 标签。如何动态传递 store_id 来激活 AJAx 调用?

这是侧边栏的代码:

<nav id="sidebar" role="navigation">
    <ul class="nav">
      <li><a href="#" onclick="???">
      {% for store in store_list %}
        <li><a href="#">
        {{ store.name }}
        {{ store.address }}</a>
      {% endfor %}  
      </li>
    </ul>
</nav>

这里是 jquery/AJAX 调用:

<script>
$(document).ready(function(){

// Submit post on submit
// Typically I would replace a with a id to specify the element selected.
  $('a').on('click', function(event){
      event.preventDefault();
  });

  function update_txns(account_id) {
    $.ajax({
      type: 'GET',
      url:'update_txns', 
      data: 'store_id',
      success: function(result){
        $('txn_table').html(result);
      } 
    });
}});

</script>

【问题讨论】:

    标签: javascript jquery ajax django django-templates


    【解决方案1】:

    这很简单,只需将id 添加到标签&lt;a&gt;,然后click 事件将提取该ID,一切就绪:

    <nav id="sidebar" role="navigation">
        <ul class="nav">
          <li><a href="#" onclick="???">
          {% for store in store_list %}
            <li><a class="store-item" id="store_{{ store.id }}" href="#">
            {{ store.name }}
            {{ store.address }}</a>
          {% endfor %}  
          </li>
        </ul>
    </nav>
    

    然后你的javascript:

    <script>
    $(document).ready(function(){
    
    // Submit post on submit
    // Typically I would replace a with a id to specify the element selected.
      $('.store-item').on('click', function(event){
         event.preventDefault();
         var store_id = $(this).attr('id').split('_')[1];
         // rest of the logic
      });
    }});
    
    </script>
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-04
    • 2011-07-13
    • 2021-10-31
    • 2015-05-21
    • 1970-01-01
    • 1970-01-01
    • 2016-08-12
    • 1970-01-01
    相关资源
    最近更新 更多