我有js代码
var model = {
start: newstart,
end: newstop,
imei: imei
};
$.ajax({
url: dburl,
dataType: 'json',
type: 'GET',
data: model,
success: function (data) {
speeddata = data;
if (speeddata.length !== 0) {
for (var i = 0; i < speeddata.length; i++) {
path = "path=" + speeddata[i].Latitude2 + ',' + speeddata[i].Longitude2;
var googleurl = "https://roads.googleapis.com/v1/speedLimits?"
+ path + "&key=" + roadsapikey;
+ path + "&key=" + roadsapikey;
$.ajax({
url: googleurl,
dataType: 'json',
type: 'GET',
success: function (data) {
for (var i = 0; i < data.speedLimits.length; i++) {
speedobject.push({
speedlimits: data.speedLimits[i].speedLimit
});
}
console.log(speedobject);
}
});
}
}
},
error: function () {
alert("Error");
}
});
在这段代码中,我从db获取数据并将其写入speeddata
数组,我在数组中有6个元素。
var speeddata = [{
Imei: 35745407257535, Latitude2: 50.9364, Longitude2: 3.12147, Speed: 8
},{
Imei: 35745407257535, Latitude2: 50.93918, Longitude2: 3.12485, Speed: 37
},{
Imei: 35745407257535, Latitude2: 50.93997, Longitude2: 3.12837, Speed: 7
},{
Imei: 35745407257535, Latitude2: 50.93834, Longitude2: 3.12893, Speed: 54
},{
Imei: 35745407257535, Latitude2: 50.9281, Longitude2: 3.13903, Speed: 56
},{
Imei: 35745407257535, Latitude2: 50.9219, Longitude2: 3.15888, Speed: 9
}];
在此之后我需要为speeddata
中的每个元素获取speedlimit并将其写入speedobject。
我试着像这里一样
if (speeddata.length !== 0) {
for (var i = 0; i < speeddata.length; i++) {
path = "path=" + speeddata[i].Latitude2 + ',' + speeddata[i].Longitude2;
var googleurl = "https://roads.googleapis.com/v1/speedLimits?"
+ path + "&key=" + roadsapikey;
+ path + "&key=" + roadsapikey;
$.ajax({
url: googleurl,
dataType: 'json',
type: 'GET',
success: function (data) {
for (var i = 0; i < data.speedLimits.length; i++) {
speedobject.push({
speedlimits: data.speedLimits[i].speedLimit
});
}
console.log(speedobject);
}
});
}
}
但console.log
speedobject时我有6次重复。
这是数组
因此,如果我想在表格中显示它,我将有36个条目而不是6个
我的麻烦在哪里?
感谢您的帮助。
答案 0 :(得分:1)
据我所知,你想要有6个条目,每个条目都有一个speedlimits数组,如下所示:
success: function (data) {
var speedLimits = []
for (var i = 0; i< data.speedLimits.length;i++) {
speedLimits.push(data.speedLimits[i].speedLimit);
}
speedobject.push({speedLimits: speedLimits})
console.log(speedobject);
}
答案 1 :(得分:0)
更新您的代码,例如
if (speeddata.length !== 0) {
for (var i = 0; i < speeddata.length; i++) {
path = "path=" + speeddata[i].Latitude2 + ',' + speeddata[i].Longitude2;
var googleurl = "https://roads.googleapis.com/v1/speedLimits?"
+ path + "&key=" + roadsapikey;
+ path + "&key=" + roadsapikey;
$.ajax({
url: googleurl,
dataType: 'json',
async: false,
type: 'GET',
success: function (data) {
speeddata[i].speedlimits=data.speedLimits;
}
});
}
}
更新了成功功能。
如果出现问题
,请添加评论编辑:我已将async: false,
添加到调用中,您可以在其中填写speeddata对象。
Oter方式是通过重构代码来进行回调