简体   繁体   中英

Ajax: error callback not firing

I'm having trouble getting the error callback getting called when I pass the error function as an object parameter in a function. However, when I declare it within the ajax code it works.

var ajaxSettings = new Object(); 
    ajaxSettings.error = function(request, status, error){ console.log('bad failure');};
    ajaxSettings.success = function(result) { console.log('good success');};
    uploadFile(contents, ajaxSettings)

function uploadFile(contents, settings) {
    $.ajax({
        url: uri,
        type: "PUT",
        data: contents,
        processData: false,
        dataType: "json",
        success: settings.success,
        error: settings.error
    });
}

In this case the error callback doesn't get fired. However if I write the error function declaration in the ajax code it works.

function uploadFile (contents, settings) {
    $.ajax({
        url: uri,
        type: "PUT",
        data: contents,
        processData: false,
        dataType: "json",
        success: settings.success,
        error: function(request, status, error) { console.log('bad failure'); },
    });
}

I also tried making success: settings.error and it will call that function when it succeeds. What is the reason the error callback is not getting called?

I created a fiddle using your code check it Fiddle

You should initialize the ajaxSettings before use it

Try to declare your callbacks like below:

var ajaxSettings = {}
ajaxSettings.error = function(request, status, error){ console.log('bad failure');};
ajaxSettings.success = function(result) { console.log('good success');};

... because they are probably not visible in "uploadFile" function scope.

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