var city;
function getCity(){
$.getJSON("http://ip-api.com/json/?callback=?", function(data) {
city= data.city;
alert(city);
});
}
getCity();
alert(city);
I am alerting the same city variable two times, one inside the function getcity() and another at last. But they both gives different values. Inside the function gives current city but out side the function gives undefined. I want to get current city on both.
-
1ajax is asynchronous....Pranav C Balan– Pranav C Balan2016年05月22日 12:30:17 +00:00Commented May 22, 2016 at 12:30
2 Answers 2
AJAX is asyncronous.
That means that getCity will retrieve data at some later point but your script will not stop, and will trigger alert(city) which currelty holds no value (undefined)
Use a callback like:
function getCity( callback ){
$.getJSON("http://ip-api.com/json/?callback=?", function(data) {
var city= data.city;
alert(city);
callback( city );
});
}
getCity(function( city ){
alert(city);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
1 Comment
That's because $.getJSON is asynchonous; it will go and fetch the specified URL in the background, then run the function you pass to the second parameter when it is completed. Meanwhile, you can carry on doing other stuff while it is fetching the requested data.
This means that your control flow looks something like the following:
- Declare city - value
undefined. - Call
getCity.getCitywill fire off the asynchronous request in the background.getCitythen exits.
- Print out the contents of
city- still `undefined. - At some point in the future,
getJSONwill have completed, and will call the specified function.- The callback will assign to
cityand print it out.
- The callback will assign to
There's not really a nice way to ensure that city is set after getCity has executed - you should try and move your logic that requires city to be set inside the callback instead.