将JSON从php传递到javascript

将JSON从php传递到javascript

本文介绍了将JSON从php传递到javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要本地化我的Web应用程序.由于不建议仅通过javascript进行本地化,因此我认为使用php将是一种替代选择.

I want to localize my webapp. Since localization through javascript only is not recommended I thought using php would be an alternative.

所以用php读取了一个messages.json文件,其中存储了所有本地化数据.

So with php I read a messages.json file that stores all localization data.

$json = file_get_contents("_locales/en/messages.json");

在我的Web应用程序的标题中,我根据用户的浏览器语言用php生成了一些javascript.

In the header of my webapp I generate some javascript with php according to the user's browser language.

echo "var localeObj = " . $json . ";";

所以这只是一个var,它保存着m essages.json文件中看起来像这样的所有数据

So this is just a var that holds all data from the messages.json file that looks like that

{
    "extTitle": {
        "message": "Test1"
    },
    "extName":{
        "message": "Test2"
    }
}

现在,我希望能够像

var title = getItem("extTitle");

并返回Test1.任何想法如何做到这一点?

and it returns Test1. Any idea how to do that?

我对json不太熟悉,但是如果我只是提醒localeObj,它只会给我[object Object].

I am not very familar with json but if I just alert the localeObj it gives me just [object Object].

推荐答案

var getItem = function(item) {
   return localObj[item].message;
};

您也可以随时封装您的i18n字符串...

You could always encapsulate your i18n strings too...

(function() {

   var localObj = { ... };

   window.getItem = function(item) {
       return localObj[item].message;
   };

})();

这样,其他任何变量都无法破坏您的localObj.

This way, no other variables can possibly clobber your localObj.

这篇关于将JSON从php传递到javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 04:16