getJSON returning data
I have looked through here and I realize it doesn't look like getJSON returns anything but开发者_StackOverflow a object that is unusable. The problem I am having is that I am trying to edit someone else's code to pull picture from flickr. I am trying to make a function that will return the description of the pictures. I know that it doesn't return information however there has to be a way to update a global variable or somehow pass off the information i need into another variable to return to his function. This is the jist of what I have so far.
function add_description(n){
var img_id = String(n);
var textInfo ="";
$.getJSON('http://api.flickr.com/services/rest/?method=flickr.photos.getInfo&api_key=36c8b00c47e8934ff302dcad7775d0a2&photo_id='+img_id+'&format=json&jsoncallback=?', function(data ){
textInfo = String(data.photo.description._content);
alert(textInfo);
return textInfo;
})
}
this is the code I tried after your updates George. Thanks!
var testObj=$.getJSON('http://api.flickr.com/services/rest/?method=flickr.photos.getInfo&api_key=36c8b00c47e8934ff302dcad7775d0a2&photo_id='+img_id+'&format=json&jsoncallback=?', function(data ){
textInfo = String(data.photo.description._content);
alert(textInfo);
return textInfo;
})
The first step is to assign the results to the textInfo
variable:
$.getJSON(...) {
textInfo = String(data.photo.description._content);
The $.getJSON() call is asynchronous, so your code return textInfo;
probably runs before the $.getJSON() call completes. Therefore, the textInfo
variable is still an empty string. You will need to call the other code from within the $.getJSON() call, or delay execution of the return until the asynchronous call completes.
This answer is based on the similar answer found here.
EDIT (based on your question update):
You will not be successful including the return statement within scope of $.getJSON()
. You can assign the result to the variable textInfo
as you have done, and that value will be available when $.getJSON completes.
However, you must ensure that the call has completed before attempting to accessing the value. You can use setTimeout()
, which seems messy, or you can substitue $.ajax() for your $.getJSON() call so you can use the 'async = false' option. This will force the call to complete before execution continues, allowing the variable to be populated before returning it.
The photo doesn't exist..
console.log(data);
Output:
code: 1
message: "Photo "2121" not found (invalid ID)"
stat: "fail"
精彩评论