我正在尝试为Google Maps API v3编写一个函数。基本上,我循环遍历给定形状的所有多边形点,并通过将每个点传递给PHP函数将它们添加到数据库中,该函数将数据插入MySQL。
function saveSite() {
// Create an array to hold the individual point saving results
var submission_Result = [];
var final_result = true;
// Get the general properties for this shape
var shape_ID = selectedShape.ID;
var shape_Name = document.getElementById("info_name").value;
var shape_Description = document.getElementById("info_description").value;
var shape_Type = shapesArray[shape_ID].type;
var shape_Points = selectedShape.getPath();
// Run through all points in the shape and save them
for (var i = 0; i < shape_Points.length; i++) {
var curPoint = shape_Points.getAt(i);
// Prepare the point data to be saved
var url = pageDir + "phpsqlinfo_addShapeData.php?db=" + database + "&job=" + jobnumber +
"&stype=" + shape_Type + "&snumber=" + shape_ID + "&sname=" + encodeURIComponent(shape_Name) +
"&sdesc=" + encodeURIComponent(shape_Description) + "&sseqno=" + i + "&slat=" + curPoint.lat() + "&slng=" + curPoint.lng();
// Attempt to save the shape data
downloadUrl(url, function(data, responseCode) {
if (responseCode == 200 && data.length <= 1) {
submission_Result.push(true);
} else {
submission_Result.push(false);
}
});
}
// Run through all point results and confirm correct submission of points
for (var i = 0; i < submission_Result.length; i++) {
if (submission_Result[i] == false) {
final_result = false;
}
}
// If all points were successfully saved, tell the user
if (final_result == true) {
// All points saved successfully so do something
} else {
// Something went wrong and not all points were added so do something else
}
}
我知道* downloadURL *作为异步函数运行,因此我目前无法遍历* submission_result *数组并检查是否所有点都已正确添加。 我的问题是,有什么方法可以等待所有的异步调用完成,然后检查结果数组?
也许像这样的东西?:
});
}
while (submission_Result.length < shape_Points.length) {
// Do something wait a short while
};
// Run through all point results and confirm correct submission of points
for (var i = 0; i < submission_Result.length; i++) {
任何想法都会非常感激,因为我完全难过!
提前致谢。
答案 0 :(得分:1)
你必须在传递downloadUrl
的回调中检查这一点,例如:
downloadUrl(url, function(data, responseCode) {
//...
if (submission_Result.length === shape_Points.length)
allResultsReady();
});
如果所有结果都在,则将调用函数allResultsReady
。
使用循环会阻止整个浏览器窗口,这绝对不是你想要的。