您做对了,但是没有在正确的地方进行。 jQuery.ajax不会等待响应,但会在请求得到响应时调用“成功”回调。
尝试这个:
var i, venues, allVenues=[];
$.ajax({
url: 'url',
dataType: 'json',
data: 'data'
async: true,
success: function(data) {
venues = data['response']['groups'][0]['items'];
// The following line of code does nothing, because you
// did not store it's return value. Fortunately it wasn't
// even needed
//
// JSON.parse(venues);
for(i in venues) {
allVenues.push(venues[i]);
}
// or
// allVenues.push.apply(allVenues, venues);
// or in ES6
// allVenues.push(...venues);
// or the following will create a new array instance and save it in the allVenues variable
// allVenues = allVenues.concat(venues);
/*Do something realistic with data other than logging it to console*/
console.log("Here are your updated venues:");
console.log(allVenues);
}
});
console.log("These are your old venues:");
console.log(allVenues);
编辑:您可以通过每秒将其打印到控制台来检查allVenues数组的标识是否未更改:
setInterval(function(stored) {
console.log(stored);
console.log(stored === allVenues);
}, 1000, allVenues);
编辑:要更新一个数组以仅包含另一个数组的项目,可以使用:
allVenues.length = 0;
allVenues.push.apply(allVenues, venues);
要么
allVenues.length = venues.length;
for (var i in venues) {
allVenues[i] = venues[i];
}