Accessing A Json Object Outside Its Callback Method
Solution 1:
Like mentioned in comments, your ajax request will take some time (short amount of time, but still time), so your console.log
located outside of the ajax call will execute before the ajax call is complete, showing the original, empty array.
You could add a callback parameter to your fetch
function...
so...
functionfetch (key, callback) {
var url = 'server/server.php?key=' + key
$.getJSON(url , sett = function(data) {
$.each(data, function(key, value){
names[key] = value['name'];
});
// call callback inside the getJSON callback
callback && callback.call(this, names);
});
}
Now, your callback function will have your names
array as argument one.
fetch(some_key, function(names){
console.log(names); //should work!
});
Solution 2:
I would start by trying to add your array elements to the array.
names.push(value['name']);
If you want more of dictionary approach (which it seems like you do) try this.
JavaScript dictionary with names
Also, after reading the other comments and thinking more... you may want to move your code that loops over the results into the 'success' callback.
http://api.jquery.com/jQuery.getJSON/
Good luck!
Solution 3:
I haven't tested this. But the following should work:
var names = newArray();
functionfetch (key) {
var url = 'server/server.php?key=' + key
$.ajax({
url: url,
type: "get",
success: function(data) {
$.each(data, function(key, value) {
names[key] = value['name'];
});
console.log(names); // this should still work
},
dataType: "json",
async: false
});
console.log(names); // this should now work
}
However, you really should try to stay away from synchronous requests.
Post a Comment for "Accessing A Json Object Outside Its Callback Method"