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 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器