2

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?

DarkLeafyGreen
  • 69,338
  • 131
  • 383
  • 601

1 Answers1

3

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);
        });
Pekka
  • 442,112
  • 142
  • 972
  • 1,088
  • hm I want to develop some kind of localization feature to support different languages, do you think the way I intent to do it is recommended? – DarkLeafyGreen Feb 23 '11 at 15:48
  • @ArtWork that's a big issue. See e.g. http://stackoverflow.com/questions/48726/best-javascript-i18n-techniques-ajax-dates-times-numbers-currency or http://stackoverflow.com/questions/3084675/internationalization-in-javascript.... I generally tend to pre-load all the words I am going to use in the document's head. I would expect loading translations using Ajax may often be too slow – Pekka Feb 23 '11 at 15:50