2017-05-30 42 views
0

在我的页面上,我弹出了一个要求购买确认的模式。这种模式可以通过对应于我的“商店”中的每个项目的10个不同按钮按压来触发。如果可能的话,我想这样做,使得该项目的价格{{ item.price }}在模式窗口内可见。我如何将这些信息与按钮按下一起发送?我需要定义10种不同的模态吗?Django/HTML:通过点击按钮发送信息?

<!DOCTYPE html> 

{% extends 'base.html' %} 

{% load staticfiles %} 

{% block content %} 
<div class="row centre-v"> 
    <div class="card shop-card"> 
    <div class="card-block shop-clock"> 
     <h3><span class="shop-tag">Shop</span></h3> 
     {% if items %} 
     {% for item in items %} 
     <div class="alert alert-shop" role="alert"> 
     <span class="shop-title">{{ item.perk }}</span> 
     <span class="shop-cost"><button type="button" class="btn btn-primary btn-shop" data-toggle="modal" data-target="#shopModal">Buy:&nbsp;{{ item.price }}<img class="coin-img shop-coin" src="{% static 'assets/coin.png' %}" height="20px" width="auto"></button></span> 
     <div style="clear: right;"></div> 
     </div> 
     {% endfor %} 
     {% endif %} 
     </div> 
    </div> 
</div> 

<div class="modal fade" id="shopModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> 
    <div class="modal-dialog" role="document"> 
    <div class="modal-content"> 
     <div class="modal-header"> 
     <h5 class="modal-title" id="exampleModalLabel">Purchase confirmation:</h5> 
     <button type="button" class="close" data-dismiss="modal" aria-label="Close"> 
      <span aria-hidden="true">&times;</span> 
     </button> 
     </div> 
     <div class="modal-body"> 
     This will cost you {{ item.price }} 
     </div> 
     <div class="modal-footer"> 
     <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> 
     <button type="button" class="btn btn-primary">Save changes</button> 
     </div> 
    </div> 
    </div> 
</div> 
{% endblock %} 

回答

1

正如我所看到的,您已经拥有模板中所需的所有信息,并且无需重新加载页面或使用AJAX。 我会覆盖按钮中的onclick事件。新功能将收到您想要在模态中显示的所有信息。

比方说你有你的按钮:

<button onclick="showMyModal({{ item.price }})">Buy</button> 

然后,你需要创建的js函数:

function showMyModal(itemPrice){ 
    /* populate the element with the price */ 
    document.getElementById("modal-price-element").innerHTML = itemPrice; 
    /* Show the modal */ 

} 

您可能想通过函数来​​发送更多的信息,并添加更多的数据到模态。如果您熟悉JQuery,也可以使用JQuery。

+0

工程就像一个魅力,谢谢。 – iFengo

+0

很高兴知道! –

1

在while循环中制作10种不同的模态是可能的,但这是不好的做法。正确的解决方案是使用JavaScript对服务器进行AJAX调用。

您需要制作一个JavaScript脚本,该脚本将使用该项目的ID对服务器执行AJAX调用。在Django中,您需要编写一个视图,通过使用JSON来返回价格(和其他信息)。

如果你需要做很多这些事情,我会建议看看Django REST框架。

1

至于我,正确的解决方案将创建一个模式标记。并通过AJAX调用点击按钮加载信息显示服务器。