简体   繁体   中英

Best way to implement PHP constants in Javascript

So I am using Codeignitor and I am trying to figure out the best way to share my constants with my javascript in a neat maintainable way.

1) in the view I could echo out my variables in like my footer (yuuuck!) 2) I could parse a partial view which contains a template for javascript and inject that in my view (maybe?) 3) I could dynamically create a javascript file like myJavascript.js.php and include that in my header.

What's the best maintainable way to implement PHP into JS in a MVC framework?

To keep my variables nicely wrapped I use a JSON object - that way I won't incur in issues with encoding, slashes, having to manually update the JavaScript every variable I add...

$variables_to_view['js_variables']['var_name'] = $var_name;

then pass it to the view

php_variables = <?php echo json_encode($js_variables) ?>;
alert(php_variables.var_name);

There doesn't seem to be anything wrong about echoing your variables in the script tag. In fact, frameworks like BackboneJS are encouraging you to do so for data you need to pass to your client-side code.

You can use short tag like this:

For Example: You want to use $abc variable in js, then you will need to write this in js

var abc = <?=$abc?>;

You can create php file . Something like script.js.php?outfor=1;

 <?php
  header("Content-type:text/javascript"); //can be application/javascript.
 ?>

 ABC = <?php echo $abc?>
 CBA = <?php echo $cba?>
 BAC = <?php echo $bac?> //and so on.

Some additional info . If you use "var" in function that variable will be visible only in that function and without "var"means global.

So.

function abc() 
{
  var a = 1; //only in abc()
  b=2;  //global
}

I know that in terms of programming skills it's not the best, but finally it's what I use and it's working. To make it short: I put all my constants in a xml file and I have this little script that generates two separate files with the same content, but different syntax. I am just pasting the code with my values. If it's useful for anybody, I'll be very happy to help. The xml is the simplest possible; value

<?php
define("GECOXML_PATH","../xml/geco.xml");
define("PHP_GECO_FN","../.includes/geco.php");
define("JS_GECO_FN","../js/geco.js");
echo "********   GECO (GEnerate COnstants files for PHP and JS) **********<br>";
echo "<br>";
echo "         input xml file: ". GECOXML_PATH."<br>";
echo "         output php file: ". PHP_GECO_FN."<br>";
echo "         output js file: ". JS_GECO_FN."<br>";
echo "********************************************************************<br>";

$geco = (object)xmlParse(GECOXML_PATH);
echo "<br>";
echo "<br>";
echo "************ PHP GECO ************* <br>";
echo "<br>";
$PHP =  gecoPHP($geco);
echo "<br>";
echo "<br>";
echo "************** JS GECO ************<br>";
echo "<br>";
$JS = gecoJS($geco);
writeFiles($PHP, $JS);

//****** Functions *********

function xmlParse ($url) {
        $fileContents= file_get_contents($url);
        $fileContents = str_replace(array("\n", "\r", "\t"), '', $fileContents);
        $fileContents = trim(str_replace('"', "'", $fileContents));
        return simplexml_load_string($fileContents);
    }

function writeFiles($PHPcontent, $JScontent)
{
            echo "<br> PhP ok:". file_put_contents(PHP_GECO_FN, $PHPcontent)  . "<br>";
            echo "<br> JS ok:" . file_put_contents(JS_GECO_FN, $JScontent) . "<br>";
}

function gecoPHP($gecoOBJ)
{
    foreach ($gecoOBJ as $key => $value)
    {
        if (is_numeric(str_replace(" ","",$value)))
            {
                $line = "define(\"" . $key . "\",". intval($value) .  ");\n";
            }
            else
            {
                $line = "define(\"" . $key . "\",\"". $value .  "\");\n";
            }
        $phpContent = $phpContent . $line;
     echo $line."<br>";
    }
   return "<?php\n"$phpContent."?>";
}

function gecoJS($gecoOBJ)
{
    foreach ($gecoOBJ as $key => $value)
    {
        if (is_numeric(str_replace(" ","",$value)))
            {
                $line = "var " . $key . "=". $value . ";\n";
            }
            else
            {
                $line = "var " . $key . "=\"". $value . "\";\n";
            }
        $JSContent =  $JSContent . $line;
    echo $line."<br>";
    }
   return $JSContent;
}
?>

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