现在前 5 页结果中的每个 Google 链接都是:在我的浏览器中访问过,我需要询问...
如何使 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
}, ...
有什么想法吗?我知道关于堆栈溢出还有很多其他类似的问题,但我没有找到任何解决这个问题的方法。
谢谢
更新
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);
最佳答案
首先,如其他地方所述,您需要一个在范围内的变量,其次您需要确保在调用回调之前不会对其进行求值。
确保这一点的唯一方法是在成功回调方法中调用 _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);
},
}
});
}
回调是异步的,这意味着它们在某个时间点被调用,而不是由代码行的顺序决定。 如果您知道在执行成功回调之前永远不会调用使用返回数据的代码,并且您需要保留数据,则可以将代码更改为
_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);
}
}
},
}
});
}
关于javascript - 在 jQuery 中的 ajax 调用之外访问 JSONP 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14597786/