如何使用 Django 模板中的动态 DOM 元素通过 jquery 进行 Ajax 调用

How to make an Ajax call through jquery with dynamic DOM elements in Django templates?

本文关键字:元素 jquery 进行 调用 Ajax DOM 动态 Django 何使用      更新时间:2023-09-26

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

我滔滔不绝,我必须将存储 id 传递给 jquery -> Ajax 以提取有关存储的信息,然后更新 DOM。

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

这是侧边栏的代码:

<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>

很简单,只需添加并id到标签<a>,然后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>