【问题标题】:return true or false after ajax post in parent function?在父函数中的ajax发布后返回true或false?
【发布时间】:2015-12-05 18:28:36
【问题描述】:

我想在进行这个 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 之类的东西来做这件事......

【问题讨论】:

标签: javascript jquery ajax asynchronous return


【解决方案1】:

您可以使用 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();
        }
    });
}

【讨论】:

    【解决方案2】:

    我将脱离 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 条件语句中使用异步函数时,可以使用

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

    【讨论】:

      猜你喜欢
      • 2015-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-11
      • 2017-08-19
      • 1970-01-01
      • 2016-04-16
      相关资源
      最近更新 更多