2015-09-09 241 views
1

我想使这一AJAX调用后返回true或false:我想要什么返回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和东西...

+3

可能重复[如何返回从异步调用的响应?](HTTP://计算器.COM /问题/ 14220321 /如何对返回的响应,从-的异步调用) – Xufox

回答

3

你可以使用承诺或回调来实现你想要的东西。

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(); 
     } 
    }); 
} 
1

我要熄灭的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 
    } 
});