我想写一个代码,其中有几个货币的数组。我想获得数组中这些货币组合的利率。
即如果我有这样的数组:
['美元','澳元','英镑'],然后我想获得转换的价值,如:
USD-> AUD,USD-> GBP,AUD-> USD,AUD-> GBP,GBP-> USD,GBP-> AUD。要获得实时汇率,我在这里使用货币api:http://currency-api.appspot.com
因为我有一种重复,我已经用于循环来创建json的ajax请求的url。在我创建了url之后,我将它们保存到了ur数组,以及curr数组中的转换名称,这样我就可以使用相同的索引来引用ur数组和curr数组。
现在是诡异的部分
循环显示网址并获取每次使用$ .each的货币转换的实时货币值,并在$ .each内部获得$ .ajax。 现在我得到了我已经将它存储到数组的值 - an_array。
最后(在$ .end和$ .ajax之外),当我尝试打印an_array的值时,它是空的。
var currencies = ['AUD','USD','INR','GBP'];
var ur = [];
var curr = [];
var curr_val = [];
var an_array = [];
for (var i = 0; i < currencies.length; i++) {
for (var j = 0; j < currencies.length; j++) {
if (i != j) {
cont = 'https://currency-api.appspot.com/api/' + currencies[i] + '/' + currencies[j] + '.jsonp';
tex = currencies[i] + ' ' + currencies[j]
curr.push(tex);
ur.push(cont);
}
}
}
$.each(ur, function (index, value) {
$.ajax({
url: value,
dataType: "jsonp",
data: {amount: '1.00'},
success: function (response) {
result = response.rate;
an_array.push(result);
}
});
});
console.log(an_array)
/*This is returning [], but should return array with values.
I can't move this line from here, to inside,
I have logged it here because I want to check whether its working,
I want to perform calculations for the values coming out from here.*/
注意:1)我已经尝试过ajax的.done()方法 2)我认为这是一个异步问题,我也尝试了控制台返回的回调函数,没有回调函数错误
答案 0 :(得分:2)
这绝对是一个异步问题。您可以使用jQuery deferreds轻松完成此操作。
$.when.apply($, $.map(ur, function(value, index) {
return $.ajax(...) /* without "success" */
}).then(function(results) {
...
console.log(...);
});
在幕后,when
统计您的完成次数,当所有请求都完成后,执行then
处理程序。
不使用延迟的低技术解决方案是手动完成所有操作:
var totalAjaxCalls = ur.length;
$.each(ur, ...
...
success: function(response) {
result = response.rate;
an_array.push(result);
if (!(--totalAjaxCalls)) {
console.log("All results available");
console.log(results);
}
}
...
答案 1 :(得分:1)
var ur = [];
var curr = [];
var curr_val = [];
var an_array = [];
var calculationWithResult = function( myArrayForCalculation ){
// Make your calculation here
console.log( 'Every call has been made : ' , myArrayForCalculation );
}
for(var i=0;i<currencies.length;i++){
for(var j=0;j<currencies.length;j++){
if(i!=j){
cont = 'https://currency-api.appspot.com/api/'+currencies[i]+'/'+currencies[j]+'.jsonp';
tex = currencies[i]+' '+currencies[j]
curr.push(tex);
ur.push(cont);
}
}
}
var numberOfURL = ur.length;
console.log('we wait for ' + numberOfURL + ' ajax call ');
$.each(ur,function(index,value){
$.ajax({
url: value,
dataType: "jsonp",
data: {amount: '1.00'},
success: function(response) {
numberOfURL = numberOfURL-1
console.log('rest of ajaxCall : ' + numberOfURL);
result = response.rate;
an_array.push(result);
if(numberOfURL===0) calculationWithResult( result ); // make your stuff
console.log(an_array);//<-------HERE
}// |
// |
// |
});// |
});// |
// |
//console.log(an_array) |----------------- MOVE THIS
&#13;
答案 2 :(得分:1)
为什么不使用像this这样的东西:
var currencies = { "USD": {},"AUD": {},"GBP": {} };
var currencyValuesLength = Object.keys( currencies ).length * ( Object.keys( currencies ).length - 1 );
// when all done
function whenAllDone() {
$.each( currencies, function( currency_from, values ) {
$.each( currencies[ currency_from ], function( currency_to, value ) {
$( document.body ).append( $( "<div>" + currency_from + " -> " + currency_to + " = " + value + "</div>" ) );
} );
} );
}
// get values
function getValues() {
$.each( currencies, function( currency_from, values ) {
$.each( currencies, function( currency_to, value ) {
if ( currency_from != currency_to ) {
$.ajax( {
url: "https://currency-api.appspot.com/api/" + currency_from + "/" + currency_to + ".jsonp",
dataType: "jsonp",
data: {
amount: "1.00"
},
method: "POST",
success: function( response ) {
currencies[ currency_from ][ currency_to ] = response.rate;
var currentLength = 0;
$.each( currencies, function( currency, values_temp ) {
currentLength += Object.keys( values_temp ).length;
} );
if ( currentLength == currencyValuesLength ) {
whenAllDone();
}
}
} );
}
} );
} );
}
// onload
$( function() {
getValues();
} );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>