包括成功/失败jQuery / Ajax功能

Including Success / Fail to jQuery / Ajax function

本文关键字:Ajax 功能 jQuery 失败 成功 包括      更新时间:2023-09-26

我使用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
});

Aman的代码在评论中起作用了,他的后续答案似乎是更简单和更正式的解决方案-但对于其他任何打算使用我的业余代码的人来说,这里是基于Aman评论的最终结果:

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 request Success
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
// Process post-results request Fail
posting.fail(function(data){
$(document.getElementById('contentss').style.display='none');
alert ("Failed");
}); // eof Process post-results request Fail
// Process post-results request Success & Fail
posting.always(function(data){
$("html, body").animate({ scrollTop: 0 }, "slow");
}); // eof Process post-results request Success & Fail
} // eof function
}); // eof main document ready

我在发帖中使用的函数。失败和张贴。当然,总是(现在)测试的占位符,并且最终会对用户更友好一点,提醒他们出现了问题。也是为了回答我自己最初的问题的一部分,当我拔掉WAMP服务器的插头并试图将产品添加到购物车时,它工作了,所以我假设它会在失去互联网连接时工作。

我不喜欢jQuery的承诺实现(我不是唯一一个)。在这种情况下,我的理由是:

var jqxhr = $.post( "example.php")
.done(function(data) {
  // You can get your data, but...
})
.fail(function() {
  // What is the error? Do I get a code? jQuery docs don't say...
  alert( "error" );
})

一般来说,我更喜欢在jQuery中使用长手语法处理AJAX请求。$.post方法是一种简写方法,据说它使开发人员的工作更容易。但它通过隐藏某些配置选项来实现这一点(长期的经验告诉我,在将应用部署到真正的服务器之前,我几乎总是需要这些配置选项)。

所以我更喜欢$.ajax方法,它暴露了非常有用的错误处理程序errorstatusCode。所以你可以这样重写你的代码:

$.ajax({
    type: 'POST',
    url: this.Form.attr("action"),
    data: this.Form.serialize(),
    success: function(data) {
        // The rest of your success function
        // i.e. from posting.done
    },
    error: function(xhrReq, textStatus, errorThrown) {
        // The rest of your error handling code
        // i.e. from posting.fail
        // You can also retry the request or report the specific error
    },
    statusCode: // notice: statusCode singular
    {
        // Plain object syntax with integer status codes as the keys
        403: function() {
            alert("403 Forbidden. You do not have permission for this action.");
        },
        500: function() {
            alert("500 Internal Server Error. Try again later.");
        }
    }
});

文档对error处理程序是这样说的:

误差


类型:Function(jqXHR jqXHR, String textStatus, String errorThrown)
请求失败时调用的函数。该函数接收三个参数:jqXHR(在jQuery 1.4中)。x, XMLHttpRequest)对象,一个描述发生的错误类型的字符串和一个可选的异常对象(如果发生了)。第二个参数可能的值(除了null)是"timeout", "error", "abort"answers"parsererror"。当HTTP错误发生时,errorThrown接收HTTP状态的文本部分,例如"未找到";或"内部服务器错误";从jQuery 1.5开始,错误设置可以接受一个函数数组。每个函数将依次调用。注意:这个处理程序不会被跨域脚本和跨域JSONP请求调用。这是一个Ajax事件

关于statusCode处理程序:

statusCode(默认值:{})
类型:PlainObject
数字HTTP代码和函数的对象,当响应具有相应的代码时将调用这些代码。例如,当响应状态为404时,下面的代码将发出警报:(见上文)

如果请求成功,状态码函数采用与成功回调相同的参数;如果它导致错误(包括3xx重定向),它们采用与错误回调相同的参数。

也就是说,如果你有一个可行的解决方案,那就去做吧。但是请记住,如果您的编程需求变得过于复杂,那么必须去掉辅助轮。