简体   繁体   English

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

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

I have a sidebar that contains a list of user's favorite stores. 我有一个侧边栏,其中包含用户喜欢的商店的列表。 I would like to be able to click on the store element (eg stores, address) and be able to pull information on that element (eg store sales) and update the sales table called 'txn_table'. 我希望能够单击store元素(例如,商店,地址),并能够提取有关该元素的信息(例如,商店销售)并更新称为“ txn_table”的销售表。

I am gussing I have to pass the store id to the jquery -> Ajax to pull information on the store and then update the DOM. 我猜我必须将商店ID传递给jquery-> Ajax,以获取商店中的信息,然后更新DOM。

The issue is different users may have different stores in their list so I can't preassign id tag to each list element. 问题是不同的用户可能在其列表中拥有不同的商店,因此我无法将ID标记预先分配给每个列表元素。 How do I dynamically pass the store_id to activate the AJAx call? 如何动态传递store_id来激活AJAx调用?

This is the code for the sidebar: 这是侧边栏的代码:

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

Here is the jquery/AJAX call: 这是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>

That's easy, just add and id to the tag <a> , then the click event would extract that id and you are all set: 这很简单,只需将< idid添加到标签<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>

Then your javascript: 然后你的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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM