multiple ajax call to single function javascript

梦想与她 提交于 2021-02-10 16:07:28

问题


I have 3 ajax call. Data from each ajax call is passed to john_doe();

Call 1

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

    john_doe(data1);
});

Call 2

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

    john_doe(data2);
});

Call 3

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

    john_doe(data3);
});

Main function

function john_doe(param){
console.log(param); //Print data from all three ajax call.
}

How to separate data1, data2 and data3 in john_doe function? because I need to carry out arithmetic operation.

Currently,

Input

data1 = one,two,three
data2 = four
data3 = five

Output

console.log(param) would give output as

one
four
five

I want output as

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

I dont have control over the data. How to access data1, data2 and data3 separately?


回答1:


Quick and dirty solution is simply pass in an identifier, why is this dirty because it isn't really extensible with respect to adding say 4th or 5th call each time you do this you need to add more identifiers and your if statement in the main method will end up pretty ugly at one point. But that said sometimes "Keeping It Simple" is ok.

Main function:

function john_doe(identifier, param) {

    // best to use something more readable then numbers
    if(identifier == 1) {    
       console.log(param); //Print data from all ajax call 1.
    } else if(identifier == 2) {
       console.log(param); //Print data from all ajax call 2.
    } else if(identifier == 23) {
       console.log(param); //Print data from all ajax call 3.
    } else {
       // handle bad id
    }
}

In your ajax calls, pass in the right identifier, for example Call 2:

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

    // numeric 2 in in the first param is your identifier
    john_doe(2,data2); });



回答2:


Using promises you can access all the data in Promise.all() callback and do whatever you need with it all at once. Assumes using jQuery 3+. Can use $.when in older versions

  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)
  })

DEMO




回答3:


Adding a param to let you know where it is being called from

Call 1

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

    john_doe('call1',data);
});

Call 2

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

    john_doe('call2',data);
});

Call 3

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

    john_doe('call3',data);
});

Main function

function john_doe(call,data){
    console.log('Called from : ' + call);
    console.log(data); //Print data from all three ajax call.
}



回答4:


How about this? Declare an object container to hold your response data values and your arithmetic operation function.

var myParams = {
    all_params: [],
    getParams: function(){
        return this.all_params;
    },
    setParam: function(index, data){
        this.all_params[index] = data;
    },
    yourArithmeticOperation: function(){
        console.log(this.all_params); // your actual logic using all 3 ajax response data
    }
}

Then, in your ajax calls:

// call 1
$.ajax({
    url: url1,
    dataType: "JSON",
    type: "GET",
}).success(function(data){
   myParams.setParam(0, data); // add ajax 1 response data
});

// call 2
$.ajax({
    url: url1,
    dataType: "JSON",
    type: "GET",
}).success(function(data){
   myParams.setParam(1, data); // add ajax 2 response data
});

// call 3
$.ajax({
    url: url1,
    dataType: "JSON",
    type: "GET",
}).success(function(data){
   myParams.setParam(2, data); // add ajax 3 response data
});

In case you need all your response data,

// after all three ajax calls
params = myParams.getParams();
console.log(params);

And finally, your arithmetic operation,

myParams.yourArithmeticOperation();



回答5:


try adding async: false to your ajax calls

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

    john_doe('call1',data);
});


来源:https://stackoverflow.com/questions/43309387/multiple-ajax-call-to-single-function-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!