简体   繁体   English

麻烦将javascript变量设置为php输出

[英]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. 我正在尝试将javascript变量设置为php脚本的输出,但是JS变量继续求值为PHP代码段的文字输出。

Even when I do something as simple as this in my .js file: 即使我在.js文件中执行了以下操作,也很简单:

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

the JS variable comes out as: JS变量显示为:

"<?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. 正如上面的评论所指出的那样,解决方案是在.php文件中运行该Java代码段。

I just moved that line to the 我刚把那条线移到

<script>

section of my main .php file, and it works. 我的主要.php文件的“部分”,并且可以正常工作。

In order for those php tags to run, they need to be in a file that actually executes php (so a .php file). 为了使这些php标签运行,它们必须位于实际执行php的文件中(因此是一个.php文件)。 Putting that line in a script tag at the top of the head in a php file will solve your problem. 将这一行放在php文件头部顶部的脚本标签中,将解决您的问题。 (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文件,则可以将AddType application/x-httpd-php .html到根目录中的.htaccess文件中。这也将使php执行html文件。 )

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM