将javascript注入我的应用程序的更好方法是什么?

时间:2010-07-07 09:35:00

标签: php javascript html code-injection

根据用户的偏好,我在我的应用程序中注入一个jason_encoded(转换数组),后来转换为javascript对象并由应用程序使用。在您看来,哪种方式更好?

解决方案1:

<head>
   <script type="text/javascript" src="lang.php"></script>
</head>

解决方案2(代码在index.php中执行):

<head>
       <?php
           require_once(database_connect.php);
           //Prepare $myDictionary...

           $dictionary = json_encode($myDictionary);
           echo ("
              <script type='text/javascript'>
                 var dictionary=". $dictionary .";
              </script>
           ");

           require_once(database_close.php);
       ?>
</head>

我目前正在使用第一个解决方案,因为我可以缓存结果,但我不知道是否将所有PHP代码(包括require / include函数)放在index.php中是好还是坏。感谢您的任何建议。

2 个答案:

答案 0 :(得分:3)

我会选择第一版 - 它看起来更整洁并且分开了。

答案 1 :(得分:3)

将HTML标记作为字符串回显(例如echo“&lt; p&gt; ...&lt; / p&gt;”)通常是使用PHP的不好方法。使用alternative syntax并避免混合过多的PHP和HTML。为了更接近MVC方法,它应该是这样的。

<?php

require_once(database_connect.php);
$dictionaryJSON = json_encode($myDictionary);
require_once(database_close.php);

// end of controller, begin of view
?>
<head>
    <script type='text/javascript'>
        var dictionary=<?php echo $dictionaryJSON ?>;
    </script>
</head>

你的第一种方式看起来也很好,特别是当你需要缓存时。