简体   繁体   中英

Accessing JSONP data outside of ajax call in jQuery

Now that every google link in the first 5 pages of results is :visited in my browser, I needed to ask...

How can I get the JSON data working so that I can access it/manipulate it in other methods?

_otherMethod: function() {

  // END GOAL OF WHERE I WANT THIS TO BE AVAILABLE
  var text = this._requestText();
},

_requestText: function() {
  var url = 'http://api.flickr.com/services/feeds/photos_public.gne?format=json';
  $.ajax({
      type: 'GET',
      url: url,
      async: false,
      dataType: 'jsonp',
      success: function(data) {

        // works here
        console.log(data);

        // works here as well & fires local function
        testing(data);

        // doesnt store
        var testvar_1 = data;
      }
  });

  // undefined
  console.log(testvar_1);

  function testing(data) {
    // logs when called from above
    console.log(data);

    // doesnt store
    var testvar_2 = data;
  }

  // undefined
  console.log(testvar_2);

  // havent found this yet...
  return magicVariableThatLetsMeAccessJSON
}, ...

any ideas? i know theres a lot of other similar questions on stack overflow, but i have found nothing that solves this.

thanks

UPDATE

var storage;
var yourobj = {
    _otherMethod: function() {
      // END GOAL OF WHERE I WANT THIS TO BE AVAILABLE
      var text = this._requestText();
    },
    _requestText: function() {
      var url = 'http://api.flickr.com/services/feeds/photos_public.gne?format=json';
      $.ajax({
          type: 'GET',
          url: url,
          async: false,
          dataType: 'jsonp',
          success: function(data) {
            storage = data;

            // logs correctly
            console.log(storage);
          }
      });
    }
}
//undefined
console.log(storage);
yourobj._requestText();
//undefined
console.log(storage);

Firstly as noted elsewhere, you need a variable that's in scope, secondly you need to make sure it's not evaluated before the callback is called.

The only way to ensure that is to make the call to _otherMethod inside the success call back method

_otherMethod: function(text) {
   //...do what ever you need to do with text
},

_requestText: function() {
  var url = 'http://api.flickr.com/services/feeds/photos_public.gne?format=json';
  $.ajax({
      type: 'GET',
      url: url,
      async: false,
      dataType: 'jsonp',
      success: function(data) {
         _otherMethod(data);
      },
      }
  });
}

callbacks are asyncronous meaning they are called at some point in time that's not determined by the sequence of code lines. If you know the code using the returned data is never going to be call before the success call back has executed and you need to hold on to the data you can change the code to

_otherMethod: null, //not strictly needed    
_requestText: function() {
  self = this;
  var url = 'http://api.flickr.com/services/feeds/photos_public.gne?format=json';
  $.ajax({
      type: 'GET',
      url: url,
      async: false,
      dataType: 'jsonp',
      success: function(data) {
         self._otherMethod = function(data){
              return function(){
                 //do what you need to with data. Data will be stored
                 //every execution of _otherMethod will use the same data
                 console.log(data);
              }
         }
      },
      }
  });
}

By adding var before your variable name, you create a local variable in the current scope.

This doesn't work:

var a = 2;

(function() {
    var a = 3;
})();

console.log(a); // 2

While this does:

var a = 2;

(function() {
    a = 3;
})();

console.log(a); // 3

Since the variable that you're trying to set is in an outer scope, get rid of var when working with it in an inner scope.

Very simple. You need a storage variable outside of the context of the callback function.

var storage;

var yourobj = {

    _otherMethod: function() {

      // END GOAL OF WHERE I WANT THIS TO BE AVAILABLE
      var text = this._requestText();
    },

    _requestText: function() {
      var url = 'http://api.flickr.com/services/feeds/photos_public.gne?format=json';
      $.ajax({
          type: 'GET',
          url: url,
          async: false,
          dataType: 'jsonp',
          success: function(data) {

            storage = data;

          }
      });


    }

}

Alternatively, storage can be a property on the same object.

might be this way:

 _requestText: function() {
   var url = 'http://api.flickr.com/services/feeds/photos_public.gne?format=json';
   var testvar_1;
   $.ajax({
     type: 'GET',
     url: url,
     async: false,
     dataType: 'jsonp',
     success: function(data) {
       console.log(data);
       testing(data);

       testvar_1 = data;
     }
   });

   // should work here
   console.log(testvar_1);

Actually you were creating a new instance of that var there.

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