gpt4 book ai didi

javascript - 包括成功/失败到 jQuery/Ajax 函数

转载 作者:行者123 更新时间:2023-11-29 19:37:04 24 4
gpt4 key购买 nike

我用了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”

所以我需要插入一个 Fail 事件,该事件将包含与 Success 类似的结果,但当然不是提醒用户该项目已成功添加,而是警告他们发生了错误。但是我也想问一下,在这种情况下是否会添加失败事件,例如,用户在将商品添加到购物车时失去了互联网连接?因为这正是我要寻找的本质......

此外,我认为我是一个糟糕的业余爱好者这一点很明显,因此对当前代码和改进的任何建议都将不胜感激。

最佳答案

JQuery ajax 回调函数

更多信息:http://api.jquery.com/jquery.post/

var jqxhr = $.post( "example.php", function() {
alert( "success" );
})
.done(function() {
alert( "second success" );
})
.fail(function() {
alert( "error" ); // if something goes wrong
})
.always(function() {
alert( "finished" ); // will always be executed, regardless of success or failure
});

关于javascript - 包括成功/失败到 jQuery/Ajax 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24872214/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com