简体   繁体   中英

jQuery .done() .fail()

What we want here is to manipulate the createSite function expected return which is {ac:failed} so when it failed .fail(failOption) will be execute else sendMail / .done(sendMail) function will execute and still holding the data from createSite function which is the {bar1:"foo1",bar2:"foo2",bar3:"foo3"}

var cSite = createSite(); //expected return if failed is {ac:"failed"} else success expected return will be {bar1:"foo1",bar2:"foo2",bar3:"foo3"}


var cSite = createSite();
cSite.done(sendMail).fail(failOption).always(alwaysOption);

function createSite() {
    return $.ajax({
        url: 'something.php',
        method: 'POST',
        data: "template_id=" + template_id + "&original_url=" + original_url + "&email=" + email + "&first_name=" + first_name + "&last_name=" + last_name
    }); //ajax
} //createSite

jQuery's fail part of the ajax promise is triggered on http statuses other than the 200 range I imagine, like 400: bad request or 500: internal server error .

If you cannot pass a fail status from something.php , there are two options. For jQuery 1 and 2:

function createSite() {
    var promise = $.Deferred();

    $.ajax({
        url: 'something.php',
        method: 'POST',
        data: "template_id=" + template_id + "&original_url=" + original_url + "&email=" + email + "&first_name=" + first_name + "&last_name=" + last_name
    }).then(function(data) {
        if(data.ac === 'failed') {
            promise.reject(failed)
        } else {
            promise.resolve(data);
        }
    })

    return promise;
}

In newer versions of jQuery (3+), you can also throw an error to trigger a fail :

function createSite() {
    return $.ajax({
        url: 'something.php',
        method: 'POST',
        data: "template_id=" + template_id + "&original_url=" + original_url + "&email=" + email + "&first_name=" + first_name + "&last_name=" + last_name
    }).then(function(data) {
        if(data.ac === 'failed') {
            throw data
        } else {
            return data
        }
    });
}

Please note that this is completely untested. The documentation for deferred is here .

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