Pass JSON from php to javascript

前端 未结 4 1933
走了就别回头了
走了就别回头了 2020-12-11 07:46

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

So with php I read a m

相关标签:
4条回答
  • 2020-12-11 08:27

    Inside messages.php:

    <?php
    header('Content-type:application/javascript');
    $messages = array(
     "yes"=>"hai",
     "no"=>"iie"
    );
    $messages = json_encode($messages);
    echo "window.messages = $messages";
    ?>
    

    Inside index.html:

    <html>
     <body>
     <script type="text/javascript" src="messages.php"></script>
     <script type="text/javascript">
      console.log(window.messages)
     </script>
     </body>
    </html>
    

    As long as you tell the browser to interpret the php file as a javascript file, you can echo anything you want.

    0 讨论(0)
  • 2020-12-11 08:28

    You can initialize javascript variable like this.

    var json = eval(<? echo $json ?>);   
    alert(json.extTitle.message+ '  '+json.extName.message);
    
    0 讨论(0)
  • 2020-12-11 08:35

    You use array syntax [], or dot syntax ., to access javascript object properties.

    Example:

    localeObj["extTitle"];
    localeObj.extTitle;
    

    I would recommend reading something like this to get more familier with JSON.

    0 讨论(0)
  • 2020-12-11 08:37
    var getItem = function(item) {
       return localObj[item].message;
    };
    

    You could always encapsulate your i18n strings too...

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

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

    0 讨论(0)
提交回复
热议问题