多个ajax调用单个函数javascript

Mur*_*dia 1 javascript ajax jquery

我有3个ajax电话.来自每个ajax调用的数据被传递给john_doe();

拨打1

$.ajax({
        url: url1,
        dataType: "JSON",
        type: "GET",
      }).success(function(data1){

    john_doe(data1);
});
Run Code Online (Sandbox Code Playgroud)

致电2

$.ajax({
        url: url2,
        dataType: "JSON",
        type: "GET",
      }).success(function(data2){

    john_doe(data2);
});
Run Code Online (Sandbox Code Playgroud)

致电3

$.ajax({
        url: url3,
        dataType: "JSON",
        type: "GET",
      }).success(function(data3){

    john_doe(data3);
});
Run Code Online (Sandbox Code Playgroud)

主功能

function john_doe(param){
console.log(param); //Print data from all three ajax call.
}
Run Code Online (Sandbox Code Playgroud)

如何在john_doe函数中分离data1,data2和data3?因为我需要进行算术运算.

目前,

输入

data1 = one,two,three
data2 = four
data3 = five
Run Code Online (Sandbox Code Playgroud)

产量

console.log(param)将输出为

one
four
five
Run Code Online (Sandbox Code Playgroud)

我希望输出为

console.log(param[0])
console.log(param[1])
console.log(param[2])

param[0] containing one,two,three
param[1] containing four
param[2] containing five
Run Code Online (Sandbox Code Playgroud)

我无法控制数据.如何分别访问data1,data2和data3?

cha*_*tfl 8

使用promises,您可以访问Promise.all()回调中的所有数据,并一次性完成所需的任何操作.假设使用jQuery 3+.可以$.when在旧版本中使用

  var urls =['data-1.json','data-2.json','data-3.json'];
  // array of ajax promises
  var reqPromises = urls.map(function(url){
    return $.ajax({
       url: url,
       dataType: "JSON",
       type: "GET"
    });
  });

  Promise.all(reqPromises).then(function(res){
     // res is array of all the objects sent to each `$.ajax` from server
     // in same order that urls are in
     var param = res.map(function(item){
       return item.val
     });

     console.log(param)
  })
Run Code Online (Sandbox Code Playgroud)

DEMO