Including PHP variables in an external JS file?

前端 未结 6 445
清酒与你
清酒与你 2020-12-06 03:15

I have a few lines of jQuery in my web application. This code is inline at the moment because it accepts a couple of PHP variables.



        
6条回答
  •  旧巷少年郎
    2020-12-06 03:56

    You could always call the function with parameters from PHP:

    somefile.js:

    function func(params) {
        //params is now from PHP
        //params.foo == "bar"
    }
    

    somefile.php:

     'bar');
    ?>
    
    
    

    I tend to go with this approach because it avoids global variables while allowing easily transporting variables.

    I like to use json_encode also because anything valid JSON is valid JS meaning you don't have to worry about escaping ' or " if you use a string and echo PHP inside of it.

提交回复
热议问题