python - Ajax Django 添加按钮未在第一次单击时添加
问题描述
所以我在 Django 中有一个动态呈现的表格,表格中的项目代表订单项目,所以对于我添加到购物车的每个订单项目,它将显示在我的购物车页面的表格中。现在我有一个数量、一个产品名称、订单项目总数等。现在我使用两个按钮,加法和减法。这是一个代码,以便您了解这个想法。
<tbody>
{% for order in orders %}
<tr>
<th scope="row">
<div class="order-quantity">
<span class="order_quantity">{{order.quantity}}</span>
<button data-url="{% url 'add' order.id %}" class="edit-quantity plus" id="plus">+</button>
<button data-url="{% url 'subtract' order.id %}" class="edit-quantity subtract" id="subtract">-</button>
</div>
</th>
<td><img src="{{order.item.product_image.url}}" alt="" width="70" height="70"></td>
<td>{{order.item.product_name}}</td>
<td> <span>₱</span> {{order.total_item_price}}</td>
</tr>
{% endfor %}
</tbody>
</table>
现在请注意,我有两个按钮,每个按钮都有一个数据 url,以便 Jquery 可以为我进行 AJAX 调用到 Django 中的指定 url。一切正常,但是当我单击添加按钮时,在我的日志中显示该项目尚未更改,而只是打印出来。但是当我第二次点击时,动作只是发生了,但不是在第一次点击期间。如何解决这个问题?
这是一个例子。
{"id": 26, "total_item_price": 6000.00, "user_id": 1, "quantity": 4, "item_id": 1, "cart_id": 11, "item": {"product_name": " Nike", "product_date_added": "2021-06-24 09:59:45.449808+00:00", "product_id": 1, "product_image": "nike.jpg", "product_stock_quantity": 6, "product_price": 1500.00, "product_description": "Nike"}}
{"id": 26, "total_item_price": 6000.00, "user_id": 1, "quantity": 4, "item_id": 1, "cart_id": 11, "item": {"product_name": " Nike", "product_date_added": "2021-06-24 09:59:45.449808+00:00", "product_id": 1, "product_image": "nike.jpg", "product_stock_quantity": 6, "product_price": 1500.00, "product_description": "Nike"}}
[26/Jun/2021 22:36:32] ←[m"GET /add/26 HTTP/1.1" 200 371←[0m
这是我的jQuery片段
$(document).ready(function() {
$("tbody").on('click', '.edit-quantity', function() {
var quantity =$(this).closest("tr").find("span.order_quantity")
$.ajax({
url : $(this).data("url"),
success : function(response) {
data = $.parseJSON(response.order)
console.log(data.quantity)
quantity.text(data.quantity)
}
})
})
})
解决方案
我认为您必须重复您的事件点击进入您的响应 AJAX 以获取新元素。例子 :
// Event click for the DOM Elements already in your page.
$('.edit-quanity').on('click', function() {
editQuantity();
}
ajaxMethod = function (url, data) {
$.ajax({
headers: {'X-CSRFToken': token},
method: method,
url: url,
data: data,
}).then(response () {
// Event click for the new element
$('.edit-quanity').on('click', function() {
editQuantity();
}
})
editQuantity = function () {
ajaxMethod(url, data);
}
我希望能帮助你。
推荐阅读
- python-3.x - Tensorflow CNN 零精度?
- kubernetes - 2 kubernetes中的负载均衡
- c - uefi 规范示例提到了 EfiCoreImageHandle。如何得到它?
- python - PANDAS - 如何根据索引中的值为整行着色
- powershell - Powershell在循环中获取枚举器
- java - 为什么 IntelliJ 调试器会跳过某些 if 语句的断点?
- laravel - 如何存储身份验证会话
- c++ - 一些 C++ 指南和使用组合创建对象
- html - 如何正确显示元素
- sql - 如何在同一个查询中使用 ISNULL 和 HASHBYTES?