简体   繁体   中英

function call with JSON-Object, which contains a function. how to get return variable outside the function?

I use the JFeed Plugin to read information about an RSS-feed in JavaScript. You can use this plugin like this:

jQuery.getFeed({
    url: 'rss.xml',
    success: function(feed) {
        alert(feed.title);
    }
});

I want to make an function, which returns the feed information like this:

function getFeed(feedUrl) {
    message ="Error";

    jQuery.getFeed({
        url: 'http://www.spiegel.de/schlagzeilen/tops/index.rss',
        success: function(feed) {
            message = feed;
        }
    });

    return message;
}

It does not work. How can I get the feed variable outside the scope of jQuery.getFeed(...) ?

It wont work this way, since method jQuery.getFeed is asynchronous and return will be called earlier.

You need to use callback to get that feeds, like this:

function getFeed(feedUrl, callback){

    message ="Error";

    jQuery.getFeed({
      url: 'http://www.spiegel.de/schlagzeilen/tops/index.rss',
      success: function(feed) {
         callback(feed);
      }
    });
}

getFeed(feedUrl, function(feeds_returned) {
  console.log(feeds_returned);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM