【发布时间】:2014-09-12 09:04:59
【问题描述】:
我使用http://api.jquery.com/jquery.post/ 帮助我构建了一个 jQuery 函数来将商品添加到购物车。
我的结果是这样的,它有效:
jQuery(document).ready(function() {
// Attach a submit handler to the form
$('form[name="cart_quantity"]').submit(function( event ) {
// Stop form from submitting normally and initiate function
event.preventDefault();
return addtocart(jQuery(this));
}); // eof Attach a submit handler to the form
// function
function addtocart(thisForm) {
// Get some values from elements on the page:
$("#contentss").fadeIn("slow");
action = thisForm.attr("action");
// Send the data using post
var posting = $.post( action, thisForm.serialize());
// Process post-results
posting.done(function(data) {
// find and put results in a div
var shoppingCartSidebox = $(data).find('div#shoppingcart').html();
var numbernotify = $(data).find('div.numbernotify').html();
$('div#shoppingcartdiv').html(shoppingCartSidebox);
$('div.numbernotify').html(numbernotify)
// initiate slideDown / slideUp
$(document.getElementById('contentss').style.display='none');
jQuery(document).ready(function() {
$("#shoppingcartdiv").slideDown();
setTimeout(function() {$("#shoppingcartdiv").slideUp()}, 7000);
}); // eof initiate slideDown / slideUp document ready
}); // eof Process post-results
} // eof function
}); // eof main document ready
我想在产品未添加到购物车的那一刻实现成功/失败事件。成功事件已经编码,基本上由后面跟“// Process post-results”的事件定义
所以我需要插入一个包含与 Success 类似结果的 Fail 事件,但当然不是提醒用户该项目已成功添加,而是警告他们发生了错误。但是我也想问一下,是否会在这种情况下添加失败事件,例如,用户在将商品添加到购物车时失去了互联网连接?因为这就是我要寻找的本质......
另外,我认为我是一个糟糕的业余爱好者,这一点很明显,所以任何关于当前代码和改进的建议都将受到高度赞赏。
【问题讨论】:
-
like posting.done(function(data){});你也可以做posting.fail(function(data){//失败时做}); posting.always(function(data){总是做,不管成功或失败});
-
@Aman 成功了!非常感谢朋友:)
-
太棒了 :D .. 祝你好运
标签: javascript jquery ajax post