return 在父函数中 ajax post 之后是真还是假?

return true or false after ajax post in parent function?

我想 return 在进行此 ajax 调用后判断真假:

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 之类的...

您可以使用 Promises 或回调来完成您想要的。

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 方法中传递回调(在您使用的实际函数完成后 "call" 的函数)。 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 条件语句中使用你的异步函数时,你可以使用

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