jquery - Return json callback data when they are available? -


i using amd , requirejs implementing following module:

define({ callweatherservice: function(x, y){       //var url = 'http://www.webservicex.net/currencyconvertor.asmx/conversionrate?fromcurrency=inr&tocurrency=aud'; // website want scrape     var url = 'http://www.webservicex.net/globalweather.asmx/getweather?cityname=' + x + '&countryname=' + y;      var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeuricomponent('select * xml url="' + url + '"') + '&format=json&callback=?';       $.getjson(yql,displaydata);      function displaydata(data){           if(data.query.results){             result = data.query.results.string.content.replace(/<script[^>]*>[\s\s]*?<\/script>/gi, '');             document.getelementbyid("asmxresult").innerhtml = result;             // return result;         }     }  } 

});

i not want modify html document in code rather return result. have tried many different methods callbacks other solutions provided in stackoverflow none seems working. e.g. following code logs result on console returns undefined:

define({   callweatherservice: function(x, y){       var url = 'http://www.webservicex.net/globalweather.asmx/getweather?cityname=' + x + '&countryname=' + y;      var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeuricomponent('select * xml url="' + url + '"') + '&format=json&callback=?';        var result;      $(function() {         var r = getresults();           result = r;     });      function getresults() {          $.getjson(yql,function(data){               if(data.query.results){                 var output = data.query.results.string.content.replace(/<script[^>]*>[\s\s]*?<\/script>/gi, '');             }             console.log(output);             return output;         });      }      return result;  } 

});

is because of using amd , requirejs or doing wrong?

i think problem you're not using callback functions.

ajax calls asynchronous, function getresults can't return something, have handle result inside callback function.

instead of returning value must this:

callback(output); 

or maybe this

callback(data.query.results.string.content.replace(/<script[^>]*>[\s\s]*?<\/script>/gi, '')); 

this should started, there many similar threads around , google can take step further.

what matters here returning values ajax trickier first appears, logics not able return data because method requires method b has maybe moved on location in method before receives needed method b. best of luck.


Comments

Popular posts from this blog

image - ClassNotFoundException when add a prebuilt apk into system.img in android -

I need to import mysql 5.1 to 5.5? -

Java, Hibernate, MySQL - store UTC date-time -