You must first sign up to be able to contribute.

Version 3 (modified by anonymous, 11 years ago)

How to initialize Javascript with JSON

When you write Javascript in template,are not the following codes written?

var mypet_type = "<?php echo $sf_data["cat"] ?>"

Javascript mixes with PHP is not understood easily. I wrote JsonHelper to resolve this problem.

1. install

Deploy this file to user lib/helper directory

2. in action

$var = array("apple" => "good" , "orange" => "nice");
$this->fruits = $var;

3. in template

<?php use_helper('Json') ?>
<php echo export_js("fruits",$fruits) ?>

4. results

<script type="text/javascript">
var fruits = {"apple":"good","orange":"nice"} ;