coderifous / jquery-localize

a jQuery plugin that makes it easy to internationalize your web site.
465 stars 142 forks source link

Can I get json value right in js ? #24

Closed david-nubee closed 11 years ago

david-nubee commented 11 years ago

Hello,

Some code is loaded in DOM by js (AJAX like), there is a way to get specific string right in the javascript ?

Thanks

alexwebgr commented 11 years ago

im not sure what you are trying to do however you access any value in a json object just by 'drilling down' lets assume the following json structure inside a json file called data

data.json

data : {
     property1 : value1,
     property2 : value2,
     property3 : value3,
     results : [
          {
                nestedproperty1 : nestedvalue1,
                nestedproperty2 : nestedvalue2,
                nestedproperty3 : nestedvalue3
          },
          {
                nestedproperty1 : nestedvalue1,
                nestedproperty2 : nestedvalue2,
                nestedproperty3 : nestedvalue3
          }
     ]
}

please note that both property names and values have to be wrapped in double quotes ' " ' in order to be considered valid json

//try to read the json file with an ajax call using jquery

code.js

$.get("data.json",function(response)
{
      console.log(response);// returns the whole structure
      console.log(response.property1); //returns value1
      console.log(response.results[0].nestedproperty1); //returns nestedvalue1

      //try to populate a certain html element 
      $(".myDiv").text(response.property1);
});

alex

coderifous commented 11 years ago

@saguenayjoe, if you wanted the translations to substitute strings in your javascript code, I would instead change those string literals to be variables and assign the translated values to those variables. @alexwebgr has kindly illustrated how you might do just that.

david-nubee commented 11 years ago

Thanks a lot it's exactly what I need.