简体   繁体   中英

Pass value from PHP to JS with Smarty?

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

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);

Define a global JS variable on your Smarty template file :

<script>
_Entrys = {$settings['frontendEntrys']};
</script>

And use on JS file :

$(document).ready(function()
{
    $('#entrys').val(_Entrys);
});

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>
{/foreach}
</select>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM