简体   繁体   中英

trouble setting javascript variable to output of php

I'm trying to set a javascript variable to the output of a php script but the JS variable continues to evaluate to the literal output of the PHP snippet.

Even when I do something as simple as this in my .js file:

var list = "<?php echo 'foo'?>";

the JS variable comes out as:

"<?php echo 'foo'?>"

When I try removing the quotes, I get parsing errors.

I've seen several examples like the above on various sites, though, so it seems like this should work.

As the comments above pointed out, the solution was to run that snippet of Javascript in a .php file.

I just moved that line to the

<script>

section of my main .php file, and it works.

In order for those php tags to run, they need to be in a file that actually executes php (so a .php file). Putting that line in a script tag at the top of the head in a php file will solve your problem. (Side-note: If you prefer to use html files instead like I do, you can add AddType application/x-httpd-php .html to your .htaccess file in your root directory. This will make php execute html files as well.)

 <html> <head> <script> var list = "<?php echo 'foo'?>"; </script> ... </head> ... </html> 

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