【发布时间】:2015-05-19 20:14:34
【问题描述】:
我需要代码像这样流动:从 calcRoute 获取值(谷歌地图距离)-> 添加到数组(?)/添加到输出字符串,直到它遍历所有值。然后追加到列表视图。
var myArray = [];
$.get( "http://www.url.com/info.php", function( data ) {
var output = "";
var imgsrc = "";
obj = jQuery.parseJSON(data);
for (i = 0; i < obj.length; i++)
{
store=obj[i].store;
for (j = 0; j < obj[i].products.length; j++)
{
productname= obj[i].products[j].productname;
price=obj[i].products[j].price;
calcRoute(function(returnValue) {
myArray.push(returnValue);
console.log("Inside callback : " + flowcounter++);
console.log("Inside callback (Array): " + myArray);
});
console.log("Array has now (J-loop) : " + myArray);
console.log("Flowcounter has now (J-loop) : " + flowcounter++);
output+='<li> <img style="margin-left: 8px" width="80" height="80" alt="sample" src="img/logo.png" align="left"/> <h3>'+ productname+' '+price+'</h3><p>Ca:'+ myArray[i] +' km.</p> </li>';
}
}
console.log("Append to list (Counter) : " + flowcounter++);
console.log("Appen to list(Array): " + myArray);
$("#prodlist").append(output).listview().listview('refresh');
});
但现在它是这样的:J-loop -> append to listview -> calcRoute。 所以在执行下一件事之前它没有值。这里的问题显然是我需要获取一个值,将其放入输出中,当它们都完成后,放入 prodlist-append。 这是 calcRoute 代码:
function calcRoute(callback) {
var start = new google.maps.LatLng(55.613520,12.534539);
var end = new google.maps.LatLng(55.713520,12.534539);
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode["DRIVING"]
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
var totalDistance = 0;
var legs = response.routes[0].legs;
for(var i=0; i<legs.length; ++i) {
totalDistance += legs[i].distance.value;
}
totalDistance = totalDistance / 1000;
totalDistance = totalDistance.toFixed(1);
myArray.push(totalDistance);
callback(totalDistance);
});
};
也添加了 logcat:
任何帮助表示赞赏。
【问题讨论】:
-
我认为你应该看看延迟调用。检查此链接,有一个很好的示例stackoverflow.com/questions/17095023/…
标签: javascript asynchronous callback