【问题标题】:Including Success / Fail to jQuery / Ajax function包括成功/失败到 jQuery/Ajax 函数
【发布时间】: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


【解决方案1】:

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
});

【讨论】:

    【解决方案2】:

    Aman 在 cmets 中的代码有效,他的后续回答似乎是更简单的解决方案和更正式的解决方案 - 但对于将使用我的业余代码的其他人来说,这是基于 Aman 的 cmets 的最终结果:

    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
    

    我在 posting.fail 和 posting.always 中使用的函数当然是(现在)测试的占位符 - 最终会在提醒用户出现问题时对用户更加友好。另外要回答我自己最初问题的一部分,当我拔下 WAMP 服务器上的插头并尝试将产品添加到购物车时,这很有效,所以我假设它适用于丢失的互联网连接。

    【讨论】:

      【解决方案3】:

      我不喜欢 jQuery 的 promise 实现(我是 not the only one)。在这种情况下,我的理由是这样的:

      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 方法是 shorthand method,据说它可以让开发人员更轻松。但它通过隐藏某些配置选项来实现这一点(长期经验告诉我,在将应用程序部署到真实服务器之前,我几乎总是需要这些选项)。

      所以我更喜欢$.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 处理程序这样说:

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

      关于statusCode 处理程序:

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

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

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

      【讨论】:

      • 谢谢。我最初的问题是有人帮我将我当前的代码转换为 $.ajax 解决方案 - 但我害怕要求看似甚至没有尝试并因此提供示例尝试。事实是,我查看了 $.ajax 解决方案的布局,但我不知道如何处理 URL 和 Data 字段以将其与我当前的代码联系起来:/ 所以我只是坚持我所拥有的,哈哈 - 但是你刚刚把它放在一个银盘上交给我,我现在肯定会使用你提供的代码:D 再次感谢!
      猜你喜欢
      • 1970-01-01
      • 2014-03-07
      • 2023-03-07
      • 1970-01-01
      • 1970-01-01
      • 2015-06-13
      • 1970-01-01
      • 1970-01-01
      • 2013-11-18
      相关资源
      最近更新 更多