[英]json object to javascript global reference
Hi I have ajax which calls json, i wanted to have this json object a javascript global reference so that I can use this reference to access json object. 嗨,我有一个调用json的ajax,我想让这个json对象成为javascript全局引用,这样我就可以使用这个引用来访问json对象了。 here is code.
这是代码。
var jsonData;
$.getJSON(url, function(json) {
jsonData = json; /*i wanted to pass this json object to global reference*/
});
nextAlbum function(){
console.log(jsonData.albums.length); /*I have to acces here*/
}
your help will be appreciated. 你的帮助将不胜感激。 here is my latest code.
这是我的最新代码。
var mysplitSlider = (function(){
var init, findTotalAlbums, countAlbum;
var jsonData;
return{
init: function(url){
$.getJSON(url, function(json) {
jsonData = json;
});
},
nextAlbum:function(){
console.log(jsonData.albums.length);
},
previousAlbum:function(){}
};
})(); })();
var url = "assets/images/detail_view_gallery/data.json"; var url =“assets / images / detail_view_gallery / data.json”;
mysplitSlider.init(url); mysplitSlider.init(URL);
please help me so that I can access reference variable/object for json. 请帮助我,以便我可以访问json的引用变量/对象。
If I've understood your question correctly, then you're running into problems with the asynchronous nature of getJSON
. 如果我已经正确理解了你的问题,那么你就会遇到
getJSON
异步性质的问题。
Since getJSON
is asynchronous your jsonData
variable will not contain any data until that asynchronous call has received a response and executed the callback. 由于
getJSON
是异步的,因此在异步调用收到响应并执行回调之前, jsonData
变量不会包含任何数据。 If you attempt to access jsonData
before that's happened, you'll likely run into errors. 如果在发生这种情况之前尝试访问
jsonData
,则可能会遇到错误。
You will need to move any code that relies upon jsonData
into the callback function. 您需要将依赖于
jsonData
任何代码移动到回调函数中。
Note, the above assumes your syntax errors are just a result of creating the question and are not part of your actual code. 请注意,上面假设您的语法错误只是创建问题的结果,而不是您实际代码的一部分。
Modified code: jsonData
would not be available immediately since getJSON
is a asynchronous call. 修改后的代码:由于
getJSON
是异步调用,因此jsonData
不会立即可用。 and your function nextAlbum
definition was not currect. 和你的函数
nextAlbum
定义不是当前的。
var jsonData ;
$.getJSON(url, function(json) {
nextAlbum (json);
jsonData = json; /*i wanted to pass this json object to global reference*/
});
function nextAlbum (json){
console.log(json.albums.length); /*I have to acces here*/
}
Remember, AJAX is Asynchronous JavaScript And XML... 请记住,AJAX是异步 JavaScript和XML ...
function nextAlbum(jsonData){
console.log(jsonData.albums.length);
/* If you want, add a global var to save json */
}
$.getJSON(url, nextAlbum);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.