This isn't really a problem of scope but of synchronicity.
When your getPreviewImage
function returns, the ajax call hasn't yet be made (it's asynchronous and the execution flow doesn't wait for the request and response to be complete), so output
is still null.
You can solve this by making a synchronous ajax call or by providing a callback to getPreviewImage
instead of using its return value.
To make a synchronous ajax call, pass false
as the async
parameter. See the doc.
To use a callback, you can do this :
$('img#test').live('click', function(e) {
e.preventDefault();
getPreviewImage(function(test){
// use test
});
});
function getPreviewImage(callback) {
$.ajax({
url: "/blah.php?v=12345",...
}).done(function (data) {
callback(data);
});
}
Using a synchronous call is easier (you just have to set a parameter to false) but the callback logic is generally preferable as it doesn't block your script and allows parallel requests.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…