问题是,我对表示对象数组的文件执行Ajax请求,然后在数组中逐个更新每个对象,然后使用JSON.stringify将数组存储在localStorage中。 在完成所有这些之后,在控制台中我获得了具有更新对象的数组,但是当我存储数组时,它是存储的旧数组。
这是我的代码。
var relaisList;
function updateRelaisList(){
$.ajax({
"dataType":"json",
"url": "assets/json/relaisList.json"
})
.done(function(response){
console.log("ajax updatedRelaisList SUCCESS");
//add lat and lng for all relaisList objects
for(var i = 0, c = response.length; i < c; i++){
addLatLng(response[i]);
}
//store the updated array in the localStorage
console.log("below is the updatedRelaisList>>>")
console.log(response)
relaisList = response
window.localStorage.setItem("foo", JSON.stringify(relaisList))
})
.fail(function(){
console.log("ajax updateRelaisList FAIL");
})
}
function addLatLng(obj){
var fullAddress = obj.name + "," + obj.address + "," + obj.zip;
$.ajax({
"dataType":"json",
"url": "https://maps.googleapis.com/maps/api/geocode/json?address=" + fullAddress + "&key=AIzaSyB67tGq_pe2p6ma3QVlkciQaL4-rKIC_UE"
})
.done(function(response){
console.log("ajax addLatLng SUCCESS");
//update the object adding 2 properties lat and lng
obj.lat = response.results[0].geometry.location.lat;
obj.lng = response.results[0].geometry.location.lng;
// console.log(obj)
})
.fail(function(){
console.log("ajax addLatLng FAIL");
})
}
随时向我询问更多详情
答案 0 :(得分:1)
您能否尝试使用以下修改过的代码。此代码将等待所有Ajax响应,并且仅在从谷歌地图获取所有纬度/经度时才将数据上传到本地存储:
var relaisList;
function updateRelaisList(){
$.ajax({
"dataType":"json",
"url": "assets/json/relaisList.json"
})
.done(function(response){
console.log("ajax updatedRelaisList SUCCESS");
addLatLng(response);
})
.fail(function(){
console.log("ajax updateRelaisList FAIL");
})
}
function addLatLng(response){
var updatedResponse =[];
//add lat and lng for all relaisList objects
for(var i = 0, c = response.length; i < c; i++){
obj = response[i];
var fullAddress = obj.name + "," + obj.address + "," + obj.zip;
$.ajax({
"dataType":"json",
"url": "https://maps.googleapis.com/maps/api/geocode/json?address=" + fullAddress + "&key=AIzaSyB67tGq_pe2p6ma3QVlkciQaL4-rKIC_UE"
})
.done(function(response_inner){
console.log("ajax addLatLng SUCCESS");
//update the object adding 2 properties lat and lng
obj.lat = response_inner.results[0].geometry.location.lat;
obj.lng = response_inner.results[0].geometry.location.lng;
updatedResponse.push(obj);
if(updatedResponse.length == response.length){
//store the updated array in the localStorage
console.log("below is the updatedRelaisList>>>")
console.log(response)
relaisList = response
window.localStorage.setItem("foo", JSON.stringify(relaisList));
}
})
.fail(function(){
console.log("ajax addLatLng FAIL");
})
}
}