-->

php constants in a javascript file [duplicate]

2019-06-21 05:17发布

问题:

Possible Duplicate:
Pass a PHP string to a Javascript variable (and escape newlines)

I'm working on a project and it's already done, but it needs one more midification and its applying language constants in javascript files.

consider we include a javascript file and in that we have something like this

            alert("YOU Have VOTED BEFORE");

easy like that , the script will alert that text

but what if we need to alert a language constant of it :

            alert("<?php echo _VOTED_BEFORE?>");

this will be worked only if echo the script like inline of my php codes ...

but, how can we read and include php constants or $vars for a outside JavaScript file ???

回答1:

There is a way of doing this using a query string in the script path

See my answer here

How to pass variable from php template to javascript

Unfortunately this will break the cache for your js file so weight your options first

<script type="text/javascript" src="script.js?flag=<?php echo _VOTED_BEFORE?>"></script>

for the sake of not writing too much code refer to the link to see how to retrieve the value



回答2:

For a cleaner structure, I think the best way is to set all the data you get from PHP in one place, i.e. in the HTML you serve via PHP:

<script>
    var MyNameSpace = {
        config:
            something: "<?php echo _VOTED_BEFORE ?>"
        }
    }
</script>

In the JavaScript file you include afterwards, you can access the value via MyNameSpace.config.something.

This makes it also easier to reuse the message.



回答3:

Actually, what you had was close to being proper.

 <?php
 // Valid constant names
 define("VOTED_BEFORE", "false");
 ?>

<script type="text/javascript">
    alert("<?php echo VOTED_BEFORE;?>");
</script>     


回答4:

If it's not a PHP file, you cannot include PHP echo functions in it. I suggest that if you want to use a PHP variable in your external js files then declare it as a global in your PHP file before you reference the external js.

<script type="text/javascript">
    var globalvar = '<?php echo _VOTED_BEFORE ?>' ;    
</script>
<script type="text/javascript" src="externalfile.js"></script>

Though it's not always a good idea to clutter the global namespace.



回答5:

You can use cookies to save these constants and read them in via JavaScript or you will have to use AJAX