dou47278 2015-03-30 11:50
浏览 365
已采纳

使用Smarty将值从PHP传递给JS?

How to pass a value from php to javascript? I'm working with smarty and i tried this but js seems to take it as a a string. The value is set to 20.

$smarty->assign('settings', $settings); //$settings is an array

$settings is coming from an file, basically it are some settings. i want to select an option in an html doc with that value but it is not working.

<select id="entrys">
    <option>5</option>
    <option>10</option>
    <option>20</option>
</select>

and in the js file then:

$(document).ready(function()
{
    $('#entrys').val("{$settings['frontendEntrys']}");
});

But no option is selected then not even the first or default value and if i try to print {$settings['frontendEntrys']} it's also not working. It just seems to be taken as a string.

BTW: Is it a good way to pass some settings with smarty or generally? How can i pass the values if i don't use smarty? Would this be correct? Is this a good way, if it's done in an html file?

<script>
    var data = <?php echo $settings['entrys']; ?>
</script>
  • 写回答

3条回答 默认 最新

  • dsnd7200 2015-03-30 11:58
    关注

    In smarty you can use: {$myarray|@json_encode} Howto generate json with smarty?

    So it would be probably something like this:

    <script>
        var data = {$settings|@json_encode}
    </script>
    

    Then you can access that in js like normal object data.entrys; less php/js mishmash more clear js code.

    $('#entrys').val(data.entrys);

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?