Reputation: 70466
I want to load a JSON file and read the following data
{
"extTitle": {
"message": "test1"
},
"extName":{
"message": "test2"
}
}
This is how I load the data
function loadLocales(){
var userLang = (navigator.language) ?
navigator.language : navigator.userLanguage;
switch(userLang){
default:
$.getJSON("_locales/ne/messages.json", function(data){
return data;
});
break;
}
}
When I try to read with the following function I get an
i18n undefined error
.
function getValue(key){
var i18n = loadLocales();
return i18n[key].message;
}
Any ideas?
Upvotes: 2
Views: 289
Reputation: 449803
This is because Ajax is asynchronous. It is not possible to return something from the success callback. (There is a "sychronous" option, but that is out of the question for a series of dictionary lookups.)
You would need to re-build your program's flow so the operation (whatever it is - populating a label or other element with the value for example) takes place in the success callback of the Ajax call.
$.getJSON("_locales/ne/messages.json", function(data){
// For example, populate an element with an item from the JSON
$("#element").html(data.message);
});
Upvotes: 3