简体   繁体   English

在jQuery中的Ajax调用之外访问JSONP数据

[英]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... 既然搜索结果的前5页中的每个google链接都是在我的浏览器中访问的,我需要问一下...

How can I get the JSON data working so that I can access it/manipulate it in other methods? 如何使JSON数据正常工作,以便可以使用其他方法进行访问/操作?

_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 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的调用

_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. 通过在变量名之前添加var ,可以在当前作用域中创建局部变量。

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. 由于您要设置的变量在外部作用域中,因此在内部作用域中使用var时要摆脱它。

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. 实际上,您正在那里创建该var的新实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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