简体   繁体   中英

Success is always fired even when the response is an error

I have an Ajax function that takes in 4 parameters. The url, the data, the success callback and error callback functions. I'm trying to make this Ajax function as reusable as possible. Here's how it looks:

function send_data(url, data, successCallback, errorCallback) {
    $.ajax({
        url: url,
        type: 'post',
        data: data,
        success: successCallback,
        error: errorCallback
    });
}

Where the success callback looks like this:

function createMessage(message) {
   console.log(message);
}

and error callback looks like this:

function createErrorMessage(message) {
   console.log(message);
}

However, when I call the Ajax function with parameters that should return a 400 error bad request, the success function is always fired regardless if it is a 200 or 400 response. I don't understand why the success callback function is firing when only the error function should be firing. However, both are firing. Why is this?

The problem is in these lines

success: successCallback,
        error: errorCallback

They both are running immediately one after the other so both are returning their values. Make an anonymous callback function on both success and error and it will work fine.

success: function() {
    successCallback();
},
error: function() {
    errorCallback();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM