用jQuery推送一个数组每个循环和jQuery ajax调用

时间:2017-01-03 10:08:41

标签: javascript jquery arrays ajax

我希望循环一个数组,如果是结果,将此结果推送到一个javascript数组,我从每个循环和ajax调用中得到它。怎么回事?

我试着这样:



var ides = ["2254365", "2255017", "2254288", "2220745", "2254452", "2255239", "2232426", "2255143", "2248513", "2254295", "2233629", "2238651", "2254901", "2238430", "2239471", "2255294", "2217888", "2242302", "2242310", "2220380", "56121236", "2255244", "2235716", "2246897"];
var iArray = [];
$.each(ides, function(index, woide) {
    $.ajax({
        url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20=%20" + woide + "&format=json",
        dataType: 'json',
        success: function(data) {
            if (data.query.results != null) {
                iArray.push(woide+': '+data.query.results.channel.item.condition.code);
            }
        }
    })
})
console.log(iArray); //this don't work

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

您的ajax调用是异步的,因此需要一些时间来填充您选择的数组。但是在ajax完成并且每个循环完成迭代之前,你的日志调用就会触发。

此时ajax仍在进行中。

你必须移动ajax的成功处理程序log

&#13;
&#13;
var ides = ["2254365", "2255017", "2254288", "2220745", "2254452", "2255239", "2232426", "2255143", "2248513", "2254295", "2233629", "2238651", "2254901", "2238430", "2239471", "2255294", "2217888", "2242302", "2242310", "2220380", "56121236", "2255244", "2235716", "2246897"];
var iArray = [];
$.each(ides, function(index, woide) {
  $.ajax({
    url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20=%20" + woide + "&format=json",
    dataType: 'json',
    success: function(data) {
      if (data.query.results != null) {
        iArray.push(woide + ': ' + data.query.results.channel.item.condition.code);
      }

      if (index === ides.length - 1) {
        console.log(JSON.stringify(iArray, 0, 0)); // <-----move it here.
      }
    }
  })
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

Try to store promises returned by the Ajax call then later you call in separate loop

var ides = ["2254365", "2255017", "2254288", "2220745", "2254452", "2255239", "2232426", "2255143", "2248513", "2254295", "2233629", "2238651", "2254901", "2238430", "2239471", "2255294", "2217888", "2242302", "2242310", "2220380", "56121236", "2255244", "2235716", "2246897"];
var pArray = [];
var iArray = [];
$.each(ides, function(index, woide) {
    var promis = $.ajax({
        url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20=%20" + woide + "&format=json",
        dataType: 'json',
    });
	
	pArray.push(promis);
})

$.each(pArray, function(index,prom){
	
	prom.done(function(data){
		if (data.query.results != null) {
                iArray.push(data.query.results.channel.item.condition.code);
        }
	});

});