jquery - How to properly call a javascript callback function -


this question has answer here:

i'm new javascript , callback function, got super simple script created function, within it, used jquery.getjson retrieve json data, return target value, when ran script, can't expected output, how should call javascript callback function?

<!doctype html> <html> <head>     <meta http-equiv='x-ua-compatible' content='ie=edge' />     <title></title>     <script type="text/javascript" src="http://code.jquery.com/jquery-2.1.4.min.js"></script> </head> <body>     <script defer="true">     var parsesheet = function(url) {         var output = "";         $.getjson(url, function(data) {             output = data.version;             console.log(output); // called after, callback         });         return output;     };     var output = parsesheet("https://spreadsheets.google.com/feeds/cells/1sufzdgg7olnxg1p_cemlwuvsbo1w65grcpzshgvrnoq/od6/public/values?alt=json");     console.log(output); // called first , log out empty string.     </script> </body> </html> 

to change callback:

    <script defer="true">     var parsesheet = function(url, callback) {         var output = "";         $.getjson(url, function(data) {             output = data.version;             callback(output); // called after, callback         });     };     var output;       parsesheet("https://spreadsheets.google.com/feeds/cells/1sufzdgg7olnxg1p_cemlwuvsbo1w65grcpzshgvrnoq/od6/public/values?alt=json", function(out){        output = out;     });     </script> 

Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -