在外面定义一个空数组,然后做一个ajax请求,请求内再嵌套一个请求,最终拼接成一个三个对象插入空数组。
最终出来的结果顺序都是不一样的,因为for循环执行,但是ajax请求是异步的。最终结果受for循环影响,每次获得的数组结果里面的对象字段顺序都不一样要怎么解决。
代码示例:
$.ajax({
url: 'http://120.76.75.179:5000/service/device_access/realData',
type: 'GET',
data: {
access_token: 'cbc7970472d055c802c2f50646da0d44179bdde05bc100d1e50c679103ab0bba8cb6ee7a63a4a4875a',
did: '000200014611127'
},
success: function(data) {
console.log(1,data);
var devId_arr = (data.collectdids.v).split(',');
var devDetail_arr = [];
for(var val in devId_arr) {
var devDetail_obj = {};
// 获取第二个接口里面的设备名称
$.ajax({
url: 'http://120.76.75.179:5000/service/device_register/get_device_info_bypid',
type: 'GET',
data: {
access_token: 'cbc7970472d055c802c2f50646da0d44179bdde05bc100d1e50c679103ab0bba8cb6ee7a63a4a4875a',
pid: devId_arr[val]
},
success:function(res){// console.log(2,res);
devDetail_obj.deviceName = res[0].name;
}
})
// 获取第三个接口里面需要的值
$.ajax({
url: 'http://120.76.75.179:5000/service/device_access/realData',
type: 'GET',
data: {
access_token: 'cbc7970472d055c802c2f50646da0d44179bdde05bc100d1e50c679103ab0bba8cb6ee7a63a4a4875a',
did: devId_arr[val]
},
success:function(res){ // console.log(3,res);
devDetail_obj.deviceID = devId_arr[val];
devDetail_obj.deviceStatus = res.totalstatus.v;
devDetail_obj.countTotal = res.count.v;
devDetail_arr.push(devDetail_obj);
}
});
}
console.log(devDetail_arr.length)
console.log(devDetail_arr)
}
})
})