jQuery Ajax成功回调失败

时间:2021-08-08 19:42:29

I'm making an ajax post request with success, failure and status code handlers. However, when the request fails with a 400 error, part of the success function is still called. Could someone please tell me why?

我正在使用成功,失败和状态代码处理程序发出ajax post请求。但是,当请求因400错误而失败时,仍会调用部分成功函数。有人可以告诉我为什么吗?

$.ajax({

        type: "POST",
        url: saveToGetTalentUrl.url,
        data: JSON.stringify(candidateList),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            $("#save_to_getTalent").replaceWith("Saved to getTalent");
            alert("New User " + response.candidate.full_name + " created successfully");
            console.log(msg);
            //normalExec(response, msg);
        },
        error: function (errormessage) {

            console.log(errormessage);
        },
        statusCode: {
            400:function(){
                alert(errors.err400);
            },
            401:function(){
                alert(errors.err401);
            },
            403:function(){
                alert(errors.err403);
            },
            500:function(){
                alert(errors.err500);
            }
        }
    });
}

When the call fails with a 400 error, the error from statusCode is displayed and the error is logged from the error function, but at the same time, the line $("#save_to_getTalent").replaceWith("Saved to getTalent"); is also called. I dont understand why

当调用因400错误而失败时,将显示来自statusCode的错误,并从错误函数中记录错误,但同时,行$(“#save_to_getTalent”)。replaceWith(“Saved to getTalent”);也被称为。我不明白为什么

1 个解决方案

#1


0  

Try set async: true to see what happens.

尝试设置async:true以查看会发生什么。

See this part in the jQuery documentation for ajax:

在jQuery文档中查看ajax的这一部分:

async (default: true)

async(默认值:true)

Type: Boolean

By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active. As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done().

默认情况下,所有请求都是异步发送的(默认情况下设置为true)。如果需要同步请求,请将此选项设置为false。跨域请求和dataType:“jsonp”请求不支持同步操作。请注意,同步请求可能会暂时锁定浏览器,在请求处于活动状态时禁用任何操作。从jQuery 1.8开始,不推荐使用async:false和jqXHR($ .Deferred);您必须使用success / error / complete回调选项而不是jqXHR对象的相应方法,例如jqXHR.done()。

So, the request by default (async: true) are sent one by one, not all together. If the POST takes a while, you may see the callback function executed before the POST request returned completely. When the first line of success is executed, it is blocked because you have a dialog popped up; meanwhile, the statusCode part is also executed; it continues to the end because nothing is blocking there.

因此,默认情况下请求(async:true)是逐个发送的,而不是全部一起发送。如果POST需要一段时间,您可能会看到在POST请求完全返回之前执行了回调函数。执行第一个成功时,它会被阻止,因为您弹出了一个对话框;同时,statusCode部分也被执行;它一直持续到最后,因为那里没有阻挡。

Debug with a dialog is not the best solution because it always blocks; you can try to change some element's value to see the execute order, like changing an <input>'s value, append a number to see if the whole number string changes or not, to see if there is a race condition of success and statusCode.

使用对话框进行调试不是最佳解决方案,因为它总是阻塞;您可以尝试更改某个元素的值以查看执行顺序,例如更改的值,附加一个数字以查看整数字符串是否发生更改,以查看是否存在成功的竞争条件和statusCode 。

Something like:

$.ajax({
    data:
    url:
    success: function(returned, status, xhr) {
        $('#testInput').val($('#testInput').val() + "1");
    },
    error: function (errormessage) {
        $('#testInput').val($('#testInput').val() + "2");
    },
    statusCode: {
        400:function(){
            $('#testInput').val($('#testInput').val() + "3");
        },
        401:function(){
            $('#testInput').val($('#testInput').val() + "4");
        },
        403:function(){
            $('#testInput').val($('#testInput').val() + "5");
        },
        500:function(){
            $('#testInput').val($('#testInput').val() + "6");
        }
    }
});

#1


0  

Try set async: true to see what happens.

尝试设置async:true以查看会发生什么。

See this part in the jQuery documentation for ajax:

在jQuery文档中查看ajax的这一部分:

async (default: true)

async(默认值:true)

Type: Boolean

By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active. As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done().

默认情况下,所有请求都是异步发送的(默认情况下设置为true)。如果需要同步请求,请将此选项设置为false。跨域请求和dataType:“jsonp”请求不支持同步操作。请注意,同步请求可能会暂时锁定浏览器,在请求处于活动状态时禁用任何操作。从jQuery 1.8开始,不推荐使用async:false和jqXHR($ .Deferred);您必须使用success / error / complete回调选项而不是jqXHR对象的相应方法,例如jqXHR.done()。

So, the request by default (async: true) are sent one by one, not all together. If the POST takes a while, you may see the callback function executed before the POST request returned completely. When the first line of success is executed, it is blocked because you have a dialog popped up; meanwhile, the statusCode part is also executed; it continues to the end because nothing is blocking there.

因此,默认情况下请求(async:true)是逐个发送的,而不是全部一起发送。如果POST需要一段时间,您可能会看到在POST请求完全返回之前执行了回调函数。执行第一个成功时,它会被阻止,因为您弹出了一个对话框;同时,statusCode部分也被执行;它一直持续到最后,因为那里没有阻挡。

Debug with a dialog is not the best solution because it always blocks; you can try to change some element's value to see the execute order, like changing an <input>'s value, append a number to see if the whole number string changes or not, to see if there is a race condition of success and statusCode.

使用对话框进行调试不是最佳解决方案,因为它总是阻塞;您可以尝试更改某个元素的值以查看执行顺序,例如更改的值,附加一个数字以查看整数字符串是否发生更改,以查看是否存在成功的竞争条件和statusCode 。

Something like:

$.ajax({
    data:
    url:
    success: function(returned, status, xhr) {
        $('#testInput').val($('#testInput').val() + "1");
    },
    error: function (errormessage) {
        $('#testInput').val($('#testInput').val() + "2");
    },
    statusCode: {
        400:function(){
            $('#testInput').val($('#testInput').val() + "3");
        },
        401:function(){
            $('#testInput').val($('#testInput').val() + "4");
        },
        403:function(){
            $('#testInput').val($('#testInput').val() + "5");
        },
        500:function(){
            $('#testInput').val($('#testInput').val() + "6");
        }
    }
});