【问题标题】:multiple ajax call to single function javascript多个ajax调用单个函数javascript
【发布时间】:2017-04-09 16:54:56
【问题描述】:

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

呼叫 1

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

    john_doe(data1);
});

呼叫 2

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

    john_doe(data2);
});

呼叫 3

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

    john_doe(data3);
});

主要功能

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

john_doe函数中的data1、data2、data3如何分离?因为我需要进行算术运算。

目前,

输入

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

输出

console.log(param) 将输出为

one
four
five

我想要输出为

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

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

【问题讨论】:

  • “分离”是什么意思?
  • 更改您的 john_doe 函数以采用另一个参数来标识第一个参数?
  • @Sorikairo 现在单个 console.log(param) 打印来自 data1、data2 和 data 3 的数据。所以我得到 value1、value2 和 value3。而 value1 来自 data1, value 2 来自 data2 等等。
  • 我不明白你的意思,是的,它应该是这样工作的,而且?
  • 可以给john_doe(data, param)加一个参数,比如john_doe(data, "firstParam")加一个if(param == "firstParam")做的事

标签: javascript jquery ajax


【解决方案1】:

使用 Promise,您可以访问 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)
  })

DEMO

【讨论】:

  • 我什至无法解释我在处理此类行为方面提出了多少问题;这太棒了!
【解决方案2】:

快速而肮脏的解决方案是简单地传入一个标识符,为什么这很脏,因为每次执行此操作时添加第 4 次或第 5 次调用都不是真正可扩展的,您需要添加更多标识符和 if 语句main 方法最终会变得非常丑陋。但是有时候“保持简单”是可以的。

主要功能:

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

在您的 ajax 调用中,传入正确的标识符,例如 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); });

【讨论】:

    【解决方案3】:

    添加一个参数让你知道它是从哪里调用的

    呼叫 1

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

    呼叫 2

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

    呼叫 3

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

    主要功能

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

    【讨论】:

      【解决方案4】:

      这个怎么样? 声明一个对象容器来保存您的响应数据值和算术运算函数。

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

      然后,在您的 ajax 调用中:

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

      如果您需要所有响应数据,

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

      最后,你的算术运算,

      myParams.yourArithmeticOperation();
      

      【讨论】:

        【解决方案5】:

        尝试将 async: false 添加到您的 ajax 调用中

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

        【讨论】:

        • 永远不要使用async: false。这一直是一种糟糕的做法,现在已被浏览器供应商弃用,并且会在控制台中抛出警告
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-08-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多