"错误“;或“;失败”;在jQuery中调用$.post Ajax

"error" or "fail" for $.post Ajax call in jQuery

本文关键字:调用 post Ajax jQuery 错误 quot 失败      更新时间:2023-09-26

如果$.post调用失败,我将尝试触发Bootstrap Growl消息。我怎么知道它是否失败了?因为后端部分(PHP脚本)返回这个JSON:

{
   "success":false,
   "errors":{
      "usuario":{
         "captcha":[
            "The captcha is not valid."
         ]
      }
   }
}

所以我在jQuery中做了这个:

$.post($form.attr('action'), $form.serialize(), function(result) {
    // ... Process the result ...
}, 'json').fail(function(result) {
    console.log("fail");
    $.growl({
        icon: "fa fa-paw",
        title: "<strong>Error en datos</strong>",
        message: "Los siguientes errores ocurrieron",
        type: "danger",
        allow_dismiss: true,
        animate: {
            enter: 'animated bounceInDown',
            exit: 'animated bounceOutUp'
        }
    });
});

但是消息或console.log()都不起作用,所以我不知道权限是.fail()还是.error(),或者所有时间都是成功的,然后我需要验证JSON中的success是否带有FALSE,这意味着有一些错误。

作为第二个小问题,我如何在JSON中查找错误字符串,以便在Growl元素的message中显示为LI?

如果响应包含http错误,例如400或500,则会触发fail子句。如果http响应是200-ok,那么就不会出现故障。

试试这个代码:

$.post($form.attr('action'), $form.serialize(), function(result) {
    //code for success
    if (result.success) {
        //TODO
    }
    //code for failure
    if (!result.success) {
        console.log("fail");
        $.growl({
            icon: "fa fa-paw",
            title: "<strong>Error en datos</strong>",
            message: "Los siguientes errores ocurrieron",
            type: "danger",
            allow_dismiss: true,
            animate: {
                enter: 'animated bounceInDown',
                exit: 'animated bounceOutUp'
            }
        });
    }//if failed
},
'json');

如果我正确解释了你的问题,我认为你将captcha失败和ajax调用失败混为一谈

ajax调用本身是成功的,这就是为什么您看不到任何ajax失败输出的原因。SUCCESSFUL调用返回的JSON包含声明captcha条目未能通过测试的信息(成功:"false")。这有道理吗?

您需要获取结果JSON中的success属性,并根据其是否为success true或false应用适当的操作。