I’m trying to assign the local var UgcItems to uploadedItems but when I try to return the value I get undefined. If I put the console.log inside of the .getJSON then I get the appropriate value. The problem with that is that the scope is inside of the function. What can I do to get the JSON out of the function?
$(function(){
var uploadedItems;
$.getJSON("GetExistingUgcItems?workItemId=1", function (UgcItems) {
uploadedItems = UgcItems;
});
console.log(uploadedItems);
});
Thank you,
Aaron
The problem you’re experiencing is that
getJSONexecutes asynchronously by default. So the assignment touploadedItemshappens after theconsole.log(uploadedItems)command completes.Instead of defining
uploadedItemsin the root function, define a method which takesuploadedItems. Put all of the code which usesuploadedItemsin this function and call it from the completed handler