对单个函数javascript的多个ajax调用 [英] multiple ajax call to single function javascript

查看:72
本文介绍了对单个函数javascript的多个ajax调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have 3 ajax call. Data from each ajax call is passed to 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?因为我需要进行算术运算.

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

当前

输入

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

输出

console.log(param)将输出为

console.log(param) would give output as

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?

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

推荐答案

简单而又肮脏的解决方案只是传递了一个标识符,这为什么又很肮脏,因为相对于每次添加说第4或第5个调用而言,它都不是真正可扩展的为此,您需要添加更多的标识符,并且main方法中的if语句将在某一时刻变得非常丑陋.但这说有时候保持简单"是可以的.

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.

主要功能:

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调用中,传递正确的标识符,例如调用2 :

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

这篇关于对单个函数javascript的多个ajax调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆