所以我正在为一个类制作一个API mashup。现在,我正在从Google Maps API获得json回复。我通过使用for循环从响应中获得5个航点。我试图解决的问题是一些坐标在死区并且没有与它们相关的图片。我想在4次迭代中的每次迭代中进行ajax调用,但是如果没有图片,那么它将迭代直到找到一个,然后返回到它停止的位置。 我尝试使用while循环以便它进行调用,并且在成功的坐标上,while循环变量将被设置为true,然后它将跳出while循环然后返回for循环,这将迭代到下一个“航点”。截至目前我没有收到错误,网站超时,可能是太多的电话?也许我正在递归地做某事?
// so this for loop divides the hundreds of steps by 1/4 of the total length.
for (i=0; i<polyPoints.length; i+=quarters) {
// gets the coords for the current iteration.
var lat = polyPoints[i][0];
var lng = polyPoints[i][1];
var hasPic = false;
var origI = i;
//while loop runs through and checks to see if the coordinate has pictures at it.
while (hasPic == false){
$.ajax({
type : "GET",
dataType : "jsonp",
ajaxI: i,
url: 'https://api.instagram.com/v1/media/search?lat='+lat+'&lng='+lng+'&distance=5000&access_token='+token,
success: function(data){
i = this.ajaxI;
//if null,increases the iteration by one, and then runs through the loop again, checking the next coordinate? I hope.
if(typeof data.data[0] === "undefined" || data.meta.code == 400){
i++;
console.log("i increased to "+i);
}else{
//if the pic is there then it assigns a random picture from the result to the images array.
images.push(data.data[Math.floor(Math.random() * data.data.length)].images.low_resolution.url);
//sets while loop to stop
hasPic = true;
//loads the current iterations coordinates for the later for loop to create markers.
waypoints.push([lat,lng]);
}
}, //data.data[0].images.low_resolution.url
error: function(data){
i = this.ajaxI;
i++;
//images.push(img/test.jpg");
}
}).responseText;
}//waypoints.push([lat,lng]);
//resets the i back to the original iteration before it got increased
i = origI;
}
答案 0 :(得分:0)
这是我的尝试,使用$.Deferred
:
function tryGetImage(firstI, maxI) {
var dfr = $.Deferred();
var inner = function(i) {
if(i >= maxI) dfr.reject();
var lat = polyPoints[i][0];
var lng = polyPoints[i][1];
$.ajax({
type : "GET",
dataType : "jsonp",
url: 'https://api.instagram.com/v1/media/search?lat='+lat+'&lng='+lng+'&distance=5000&access_token='+token,
}).done(function(data){
//if null,increases the iteration by one, and then runs through the loop again, checking the next coordinate? I hope.
if(typeof data.data[0] === "undefined" || data.meta.code == 400){
inner(i + 1);
}else{
var img = data.data[Math.floor(Math.random() * data.data.length)].images.low_resolution.url);
dfr.resolve(img, [lat, lng]);
}
).fail(function(data){
inner(i + 1);
});
};
inner(firstI);
return dfr.promise();
}
var dfrs = [];
for (i=0; i<polyPoints.length; i+=quarters) {
var dfr = tryGetImages(i, i + quarters)
dfr.done(function(img, coords) {
images.push(img);
waypoints.push(coords);
})
dfrs.push(dfr);
}
$.when.apply($, dfrs).always(function() {
console.log("All requests complete");
});
答案 1 :(得分:-2)
第14行的三倍相等(===)? 我认为你的意思是==?