我有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?
最佳答案
快速而肮脏的解决方案只是传递一个标识符,为什么会这么肮脏,因为每次执行此操作时,添加第4或第5个调用并不能真正扩展,因此您需要在main方法中添加更多标识符和if语句在某一点上将变得非常丑陋。但这有时表示“保持简单”是可以的。
主功能:
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); });
关于javascript - 对单个函数javascript的多个ajax调用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43309387/