jquery - How to properly call a javascript callback function -
this question has answer here:
- how return response asynchronous call? 21 answers
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
Post a Comment