在父函数中的ajax post后返回true或false

return true or false after ajax post in parent function?

本文关键字:返回 true false post ajax 函数      更新时间:2023-09-26

我想在ajax调用后返回true或false:

function write_csv(data, path, file) {
    $.ajax({
        url: 'functions.php',
        type: 'POST',
        data: {
            operation: 'SAVE_CSV',
            save_path: path,
            save_file: file,
            save_string: data
        },
        success: function(result) {
            console.log('write_file(' + path + file + '); -done');
            return true; /* <-- */
        }
    });
}

我想要的用例:

function make_csv () {
    /* 
    |
    V
    */
    if (write_csv(my_data, my_path, 'export.csv') == true) {
        go_on();
    }
    function go_on() {
        alert('YEAH!');
    }
}

我知道这是异步的,但也许有人有另一个想法。我不会用if之类的东西

你可以使用promise或回调来完成你想要的。

function write_csv(data, path, file, callback) {
    $.ajax({
        url: 'functions.php',
        type: 'POST',
        data: {
            operation: 'SAVE_CSV',
            save_path: path,
            save_file: file,
            save_string: data
        },
        success: function(result) {
            console.log('write_file(' + path + file + '); -done');
            callback(true); /* <-- */
        }
    });
}

:

function make_csv () {
    /* 
    |
    V
    */
    function go_on() {
        alert('YEAH!');
    }
    write_csv(my_data, my_path, 'export.csv', function(result) {
        if (result == true) {
            go_on();
        }
    });
}

我打算脱离jQuery惯例,给你一个"jQuery"的答案,因为这是你正在使用的。

在jQuery中,你可以在大多数jQuery方法中传入一个回调(一个在你正在使用的实际函数完成后"调用"的函数)。jQuery的约定是将回调作为传递给函数的最后一个参数。在您的示例中,您的write_csv()函数看起来像这样,最后一个参数是一个额外的回调:

function write_csv(data, path, file, callback){
    $.ajax({
        url: 'functions.php',
        type: 'POST',
        data: {
            operation: 'SAVE_CSV',
            save_path: path,
            save_file: file,
            save_string: data
        },
        success: function(result) {
            console.log('write_file(' + path + file + '); -done');
            callback(true);
        }
        error: function(result){
            console.log('async failed');
            callback(false);
        } 
    });
}

注意传递进来的error键和$.ajax()函数中对success键所做的更改。

现在,当你想在if条件语句中使用async函数时,你可以使用

write_csv(my_data, my_path, 'export.csv', function(response){
    if(response === true){
        go_on()
    }
    else if(response === false){
        // do something else
    }
});