2017-05-30 130 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調用點擊按鈕加載信息顯示服務器。