jquery - Calling Rest API from Javascript File: Data Return Issue -


hi have created javascript file make call rest api , data. want return data calling function html page way call works, not been able to.

html:

<html> <head>     <title></title>     <script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-2.0.3.min.js" />     <script src="jquery-g5api-1.0.0.js" />     <script type="text/javascript">            function jsfile() {                 var result = getstatus(123456);                 alert('html: '+ result);            }      </script> </head> <body>     <input id="button1" type="button" value="jsfile" onclick="jsfile()" /> </body> </html> 

query-g5api-1.0.0.js:

function getstatus(token) {      var url = 'some/url';       var result = '';      $.getjson(url,function(data)       {          //alert(json.stringify(data));       })      .always(function(xhr, status) {           alert( "finished: " + json.stringify(xhr));           result = json.stringify(xhr);       });       alert('returning result: ' + result);      return result;  } 

the sequence in alerts being called: returning result: empty_string html: empty_string finished: json_data

any suggestions on how return json data .js file calling function in html file highly appreciated.

you'll need resolve promise expected result. check out jquery deferred object api , observe (simplified) following...

function getg5status3(token) {     return $.getjson('some/url') } 

function jsfile() {     getg5status(123456).done(function(response) {         console.log(response);     }); } 

jsfiddle link - simplified demo

also, not seeing usage of token


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -