jQuery AJAX事件只触发一次
首先让我感谢@Jasen,他花了9天时间帮助我解决一个问题,他花时间帮助我对我来说意义重大。他正是在帮我解决这个问题,但在最后一秒,他们决定使用AJAX,因为联系人页面使用它,从购物车中删除项目也使用它 让我来谈谈我的问题,我有一个视图(这是MVC5),它在循环中加载选定类别的所有产品。我想使用jqueryndajax将项目添加到购物车中。这对于列表中第一个项目第一次添加到购物车时非常有效 我想我的问题是所有的按钮都有一个idAddToCart和jQuery,我编写它的方式无法决定单击哪个按钮 下面是视图的代码jQuery AJAX事件只触发一次,jquery,ajax,asp.net-mvc-5,Jquery,Ajax,Asp.net Mvc 5,首先让我感谢@Jasen,他花了9天时间帮助我解决一个问题,他花时间帮助我对我来说意义重大。他正是在帮我解决这个问题,但在最后一秒,他们决定使用AJAX,因为联系人页面使用它,从购物车中删除项目也使用它 让我来谈谈我的问题,我有一个视图(这是MVC5),它在循环中加载选定类别的所有产品。我想使用jqueryndajax将项目添加到购物车中。这对于列表中第一个项目第一次添加到购物车时非常有效 我想我的问题是所有的按钮都有一个idAddToCart和jQuery,我编写它的方式无法决定单击哪个按钮
@model IEnumerable<AccessorizeForLess.ViewModels.DisplayProductsViewModel>
@{
ViewBag.Title = "Products > Necklaces";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<link href="~/Content/Site.css" rel="stylesheet" />
<link href="~/Content/jquery.fancybox.css?v=2.1.5" rel="stylesheet" />
<link href="~/Content/jquery.fancybox-buttons.css?v=1.0.5" rel="stylesheet" />
<link href="~/Content/jquery.fancybox-thumbs.css?v=1.0.7" rel="stylesheet" />
<h2>Products > Necklaces</h2>
<div id="update-message"></div>
<p class="button">
@Html.ActionLink("Create New", "Create")
</p>
@*@using (Html.BeginForm("AddToCart", "Orders", FormMethod.Post))*@
{
<div id="container">
<div id="sending" style="display:none;"><img src="~/Content/ajax-loader.gif" /></div>
<div style="color:red" id="ItemAdded"></div>
<div class="scroll">
@foreach (var item in Model)
{
<div class="scroll2">
<div class="itemcontainer">
<table>
<tr>
<td id="@item.Id" class="divId">
<div class="DetailsLink" id="@item.Id"> @Html.ActionLink(@item.Name, "Details", new { id = item.Id })</div>
<br />
<div id="@item.Id"></div>
<div class="divPrice" id="@item.Price">@Html.DisplayFor(modelItem => item.Price)</div>
<div class="divImg"><a class="fancybox-thumbs" href="@item.Image.ImagePath" title="@item.Image.AltText" data-fancybox-group="thumb"><img src="@item.Image.ImagePath" alt="@item.Image.AltText" title="@item.Image.AltText" /></a></div>
<div> </div>
<div class="divQuantity"> Quantity: @Html.TextBoxFor(modelItem => item.Quantity, new { @id = "quantity", @style = "width:50px;", @class = "formTextBox" })</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="button" value="AddToCart" class="btn btn-default" id="AddToCart" />
</div>
</div>
<div style="height:15px;"></div>
</td>
</tr>
</table>
</div>
</div>
}
<div class="button">@Html.ActionLink("Back To Categories","Categories")</div>
<br />
</div>
</div>
@*}*@
它在进行客户端更改(仅授予一次且仅针对列表中的第一项)之前就起作用了,因为我没有更改服务器端代码,会出什么问题?
编辑#2
这就是整件事的全部
@model IEnumerable<AccessorizeForLess.ViewModels.DisplayProductsViewModel>
@{
ViewBag.Title = "Products > Necklaces";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<link href="~/Content/Site.css" rel="stylesheet" />
<link href="~/Content/jquery.fancybox.css?v=2.1.5" rel="stylesheet" />
<link href="~/Content/jquery.fancybox-buttons.css?v=1.0.5" rel="stylesheet" />
<link href="~/Content/jquery.fancybox-thumbs.css?v=1.0.7" rel="stylesheet" />
<h2>Products > Necklaces</h2>
<div id="update-message"></div>
<p class="button">
@Html.ActionLink("Create New", "Create")
</p>
@*@using (Html.BeginForm("AddToCart", "Orders", FormMethod.Post))*@
{
<div id="container">
<div id="sending" style="display:none;"><img src="~/Content/ajax-loader.gif" /></div>
<div style="color:red" id="ItemAdded"></div>
<div class="scroll">
@foreach (var item in Model)
{
<div class="scroll2">
<div class="itemcontainer">
<table>
<tr>
<td id="@item.Id" class="divId">
<div class="DetailsLink" id="@item.Id"> @Html.ActionLink(@item.Name, "Details", new { id = item.Id })</div>
<br />
<div id="@item.Id"></div>
<div class="divPrice" id="@item.Price">@Html.DisplayFor(modelItem => item.Price)</div>
<div class="divImg"><a class="fancybox-thumbs" href="@item.Image.ImagePath" title="@item.Image.AltText" data-fancybox-group="thumb"><img src="@item.Image.ImagePath" alt="@item.Image.AltText" title="@item.Image.AltText" /></a></div>
<div> </div>
<div class="divQuantity"> Quantity: @Html.TextBoxFor(modelItem => item.Quantity, new { @style = "width:50px;", @class = "formTextBox quantity" })</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="button" value="AddToCart" class="btn btn-default AddToCart" />
</div>
</div>
<div style="height:15px;"></div>
</td>
</tr>
</table>
</div>
</div>
}
<div class="button">@Html.ActionLink("Back To Categories","Categories")</div>
<br />
</div>
</div>
@*}*@
@section scripts {
<script src="~/Scripts/jQuery-jScroll.js"></script>
<script src="~/Scripts/jquery.fancybox.js?v=2.1.5"></script>
<script src="~/Scripts/jquery.fancybox-thumbs.js?v=1.0.7"></script>
<script src="~/Scripts/jquery.fancybox-buttons.js?v=1.0.5"></script>
<script type="text/javascript">
//$(function () {
// $('.scroll').jscroll({
// autoTrigger: true
// });
$('.fancybox-thumbs').fancybox({
prevEffect: 'none',
nextEffect: 'none',
closeBtn: true,
arrows: false,
nextClick: false
});
// Document.ready -> link up remove event handler
$(".AddToCart").click(function () {
//first disable the button to prevent double clicks
$(this).prop("disbled", true).prop("value", "Adding...");
$("#sending").css("display", "block");
var td = $(this).closest('td')
//traverse DOM and find relevant element
var price = parseFloat(td.find(".divPrice").prop("id")),
quantity = parseInt(td.find(".quantity").val()),
id = parseInt(td.find(".divId").prop("id"));
$.ajax({
url: "@Url.Action("AddToCartAJAX", "Orders")",
type: "POST",
data: { "id": id, "quantity": quantity, "price": price },
//if successful
success: function (data) {
successfulCall()
},
error: function (data) {
errorCall(data);
}
});
function successfulCall() {
//enable the send button
$(this).prop("disbled", false).prop("value", "Add To Cart");
//hide the sending gif
$("#sending").css("display", "none");
//display the successful message
$("#ItemAdded").text("Your item has been added to your order.");
//clear out all the values
$("input#quantity").val("0");
}
function errorCall(data) {
$(this).prop("disbled", false).prop("value", "Add To Cart");
$("#sending").css("display", "none");
$("#ItemAdded").text(data.message);
}
//alert('Clicked!');
});
//s});
</script>
}
和ShoppingCrt.cs中的AddToCart:
public void AddToCart(int id, int quantity, decimal price)
{
// Get the matching cart and product instances
var order = entities.Orders.FirstOrDefault(
c => c.OrderGUID == ShoppingCartId
&& c.OrderItems.Where(p => p.ProductId == id).FirstOrDefault().ProductId == id);
if (order == null)
{
// Create a new order since one doesn't already exist
order = new Order
{
InvoiceNumber = Guid.NewGuid().ToString(),
OrderDate = DateTime.Now,
OrderGUID = ShoppingCartId,
IsShipped = false
};
entities.Orders.Add(order);
// Save changes
entities.SaveChanges();
//add the OrderItem for the new order
OrderItem oi = new OrderItem()
{
OrderId = order.OrderId,
OrderGUID = ShoppingCartId,
ProductId = id,
ProductQuantity = quantity,
ProductPrice = price
};
entities.OrderItems.Add(oi);
entities.SaveChanges();
}
else
{
// If the item does exist in the cart,
// then add one to the quantity
order.OrderItems.Where(p => p.ProductId == id).FirstOrDefault().ProductQuantity += quantity;
}
}
希望对您有所帮助当您在循环中创建元素时,会创建重复的标识符。这使得你的HTML无效 HTML中的标识符必须是唯一的。这是预期的行为 您可以分配一个公共类,然后可以使用类选择器。在这里的示例中,我向按钮添加了
AddToCart
CSS类
HTML
我还建议您使用带有前缀的自定义属性来存储任意数据
<div class="divPrice" data-price="@item.Price"></div>
注意:相应地更改其余选择器 他是在另一个问题上帮助我的人。是的,我在lilke建议的按钮类中添加了AddToCart。在
@Html.TextBoxFor(modelItem=>item.quantity
中添加了td.find(.quantity”).val()
并在成功和错误方法中进行更改,以确保正确selectors@Satpal选中successfulCall
中的编辑#2$(此)
,并且errorCall
不引用。AddToCart
使用$(“.AddToCart”)
Instedi实现了对现有代码的更改,但现在当它调用我的ajax时,我得到一个500(内部服务器错误),我已经检查了我的权限,它们似乎是正确的。@PsychoCoder,这与权限无关,根据建议,您必须进行大量更改才能获得结果,而500表示服务器端有问题。请检查我的编辑。我知道这一定是我缺少的简单内容。@PsychoCoder,正如Satpal所指出的,是500错误是serer上出现异常的结果。您需要显示控制器代码。@PsychoCoder,返回重定向到操作(“索引”)
将无法与$一起使用。ajax()
这将帮助您=>
public ActionResult AddToCartAJAX(int id, int quantity, decimal price)
{
var cart = ShoppingCart.GetCart(this.HttpContext);
cart.AddToCart(id, quantity, price);
return RedirectToAction("Index");
}
public void AddToCart(int id, int quantity, decimal price)
{
// Get the matching cart and product instances
var order = entities.Orders.FirstOrDefault(
c => c.OrderGUID == ShoppingCartId
&& c.OrderItems.Where(p => p.ProductId == id).FirstOrDefault().ProductId == id);
if (order == null)
{
// Create a new order since one doesn't already exist
order = new Order
{
InvoiceNumber = Guid.NewGuid().ToString(),
OrderDate = DateTime.Now,
OrderGUID = ShoppingCartId,
IsShipped = false
};
entities.Orders.Add(order);
// Save changes
entities.SaveChanges();
//add the OrderItem for the new order
OrderItem oi = new OrderItem()
{
OrderId = order.OrderId,
OrderGUID = ShoppingCartId,
ProductId = id,
ProductQuantity = quantity,
ProductPrice = price
};
entities.OrderItems.Add(oi);
entities.SaveChanges();
}
else
{
// If the item does exist in the cart,
// then add one to the quantity
order.OrderItems.Where(p => p.ProductId == id).FirstOrDefault().ProductQuantity += quantity;
}
}
@Html.TextBoxFor(modelItem => item.Quantity, new {@style = "width:50px;", @class = "formTextBox quantity" })
<input type="button" value="AddToCart" class="btn btn-default AddToCart" />
$(".AddToCart").click(function() {
$(this).prop("disabled", true)
.prop("value", "Adding...");
var td = $(this).closest('td.divId')
//traverse DOM and find relevant element
var price = parseFloat(td.find(".divPrice").prop("id")),
quantity = parseInt(td.find(".quantity").val()),
id = parseInt(td.find(".divId").prop("id"));
//Your ajax call
});
<div class="divPrice" data-price="@item.Price"></div>
var price = $('.divPrice').data("price");