function get(){
$.get('/get.php', function(data) {
alert('one: ' + data)
return data;
});
}
var test = get();
alert('two:' + test);
In get.php is:
<?php echo "number"; ?>
why one alert show me
one: number
but two alert show me
two: undefined
How can i get this value outside function?
The
$.getcall is asynchronous. That means that you pass it a callback (yourfunction(data) { ... }, which gets executed with the result from the call. You can’treturnfrom inside that callback – when it is executed, your outer function (doing the$.get) has already returned. Instead, try something like this:This is a pattern you will have to get used to when writing javascript code.