2015-03-30 11:50
浏览 297


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">

and in the js file then:


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?

    var data = <?php echo $settings['entrys']; ?>

图片转代码服务由CSDN问答提供 功能建议

如何将值从php传递给javascript? 我正在使用smarty,我试过这个,但js似乎把它当作一个字符串。 该值设置为20.

  $ smarty-&gt; assign('settings',$ settings);  // $ settings是一个数组

$ settings来自一个文件,基本上是一些设置。 i想要在html doc中选择一个选项 该值但它不起作用。

 &lt; select id =“entrys”&gt; 
&lt; option&gt; 5&lt; / option&gt; 
&lt; option&gt; 10&lt;  ; / option&gt; 
&lt; option&gt; 20&lt; / option&gt; 
&lt; / select&gt; 

然后在js文件中: \ n

 $('#entrys')。val(“{$ settings ['frontendEntrys']}”); 
}  ); 

但是没有选择任何选项,甚至没有选择第一个或默认值,如果我尝试打印{$ settings ['frontendEntrys']}它也没有 工作。 它似乎只是一个字符串。

BTW:这是一个通过smarty或一般传递一些设置的好方法吗? 如果我不使用smarty,我该如何传递值? 这是正确的吗? 这是一个好方法,如果它是在一个html文件中完成的吗?

 &lt; script&gt; 
 var data =&lt;?php echo $ settings ['entrys'];  ?&gt; 
&lt; / script&gt; 
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

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:

        var data = {$settings|@json_encode}

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


    打赏 评论
  • douqin6785 2015-03-30 11:57

    Define a global JS variable on your Smarty template file :

    _Entrys = {$settings['frontendEntrys']};

    And use on JS file :

    打赏 评论
  • doudou3935 2015-03-30 11:58

    You could use this approach, which has the added advantage of synchronizing the HTML and .ini settings.

    <select id="entrys">
    {foreach $settings as $setting}
        <option {if $setting == 'frontendEntrys'}selected{/if}>{$setting}</option>
    打赏 评论

相关推荐 更多相似问题