问题
function foreignCoordinatesArray(){
var coordinates = [];
$.getJSON('/critics.json?travel_id=' + $('#foreign_travel').val(), success);
function success(ary) {
for(var a in ary){
var obj = ary[a];
coordinates.push(new google.maps.LatLng(obj.latitude, obj.longitude));
}
}
console.log(coordinates);
}
At the end coordinates will still be [] and not [{...},{...},...]. I guess this must be a problem with closures
How can I have my desired value in coordinates array?
回答1:
It's not a problem with closures but with asynchronous nature of JavaScript AJAX calls. The moment AJAX call response arrives (and your success function is called, propagating coordinates
array) it is way after you logged in that array - which was empty at that time.
I guess you want to somehow return the coordinates
from foreignCoordinatesArray()
function. As you can see you cannot use return
:
function foreignCoordinatesArray(){
var coordinates = [];
$.getJSON('/critics.json?travel_id=' + $('#foreign_travel').val(), success);
function success(ary) {
//...
}
return coordinates;
}
Instead you should pass a callback function that will receive coordinates
:
function foreignCoordinatesArray(coordinatesCallback){
var coordinates = [];
$.getJSON('/critics.json?travel_id=' + $('#foreign_travel').val(), success);
function success(ary) {
//...
coordinatesCallback(coordinates);
}
}
BTW you should escape $('#foreign_travel').val()
before using it as part of the URL.
回答2:
The problem isn't with "closures," per se, but with asynchronous programming. The success function won't be called until the JSON has been fetched, which will pretty much always be long after your foreignCoordinatesArray()
function has returned. In general, when you're using an asynchronous function like $.getJSON()
, any code outside the callback shouldn't assume the callback has already run, because that is not generally a safe assumption.
The solution in this case is to move your console.log(coordinates)
into the success function.
回答3:
The callback is happening after the console.log()
is executed. If you move console.log()
into the callback function you should get the expected output.
function foreignCoordinatesArray(){
var coordinates = [];
$.getJSON('/critics.json?travel_id=' + $('#foreign_travel').val(), success);
function success(ary) {
for(var a in ary){
var obj = ary[a];
coordinates.push(new google.maps.LatLng(obj.latitude, obj.longitude));
}
console.log(coordinates);
}
}
来源:https://stackoverflow.com/questions/11004822/get-variable-from-callback-function