【问题标题】:both .done and .fail fires togheter.done 和 .fail 一起触发
【发布时间】:2017-01-04 12:13:23
【问题描述】:

我有这个 JS:

$('.save').click(function(e){
            var row = $(this).closest('tr');
            var button = $(this);
            var myParams = new Object();
            myParams.id = row.find('.id').text();
            myParams.data = row.find('.data').text();
            myParams.descrizione = row.find('.descrizione').text();
            myParams.movimento = row.find("select[name='tipo_mov']").val();
            myParams.importo = row.find('.importo').text();
            myParams.from = 'carta';
            var params = JSON.stringify(myParams);
            $.post( "edit_mov.php", params)
             .done(function( data ) {
                bootbox.alert("Movimento aggiornato correttamente");
                button.toggle().prev('.edit').toggle();//ripristino il pulsante di edit;
                row.removeClass('info').addClass('success').find('.tbe').attr('contenteditable', false).css('color','');
                row.find('.tipo_mov').toggle();
                setTimeout(function () { 
                    row.removeClass('success');
                }, 2000);
            })
             .fail(bootbox.alert("UPS! Something went wrong"));

        });

这样做是为了使用 AJAX 请求更新表行。 负责更新的 PHP 页面将返回 200 或 500,具体取决于查询是否成功:

if($count==0){
    http_response_code(500);
}else{
    http_response_code(200);
}

如果我尝试使用将失败的查询,我的 JS 将仅在 .fail 中显示警报。 如果我尝试使用会成功的查询,那么我将同时看到警报(.done 和 .fail)。

我还尝试将 .done 替换为 .success buth,但结果相同。我做错了什么?

【问题讨论】:

标签: javascript jquery ajax


【解决方案1】:

你还应该使用.fail中的函数:

.fail(function() {
    bootbox.alert("UPS! Something went wrong");
});

否则括号内的代码总是被执行。

【讨论】:

    【解决方案2】:

    根据文档。

    https://api.jquery.com/jquery.post/

    var jqxhr = $.post( "example.php", function() {
      alert( "success" );
    })
      .done(function() {
        alert( "second success" );
      })
      .fail(function() {
        alert( "error" );
      })
      .always(function() {
        alert( "finished" );
      });
    

    .fail 应该提供一个函数

    【讨论】:

    • 那么你也应该对 jQuery 文档页面投反对票。这是您可以做什么的示例。
    • 这是一个关于 done 、 fail 和 always 回调的结构的示例。我不知道为什么人们在没有适当考虑答案的情况下投票否决
    猜你喜欢
    • 2015-12-21
    • 2017-09-10
    • 2023-03-23
    • 2017-04-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-05
    • 2020-02-28
    • 2017-06-08
    相关资源
    最近更新 更多