简体   繁体   English

Javascript文件中的PHP变量

[英]PHP variable in Javascript file

I have a variable I need to drop into a javascript file and can't seem to get any results. 我有一个变量,我需要放入一个javascript文件,似乎无法得到任何结果。 I've tried making the .js into a php and adding an echo but it doesn't work. 我已经尝试将.js变成一个php并添加一个echo但是它不起作用。

I have a file that calls this in it 我有一个文件,在其中调用它

<script type="text/javascript" src="/file.php"></script>

Inside of file.php I have this line 在file.php里面我有这一行

style: {
    color: '#<?php echo $_SESSION['colorOne']; ?>'
}

Everything works perfect when I replace the php with an actual color (#FFFFFF). 当我用实际颜色(#FFFFFF)替换php时,一切都很完美。 I run into problems when I add the php. 我添加php时遇到问题。

PHP can emulate any content you'd like, even Images, PDF and Office files. PHP可以模拟您喜欢的任何内容,甚至是图像,PDF和Office文件。

First, don't confuse Javascript with CSS. 首先,不要将Javascript与CSS混淆。

<link rel="stylesheet" href="/file.php">

At the beginning of the file.php , make sure you start the session: file.php的开头,确保启动会话:

<?php
session_start();
?>
.style: {
    color: #<?php echo $_SESSION['colorOne']; ?>;
}

If this does not work, you should debug if your session is init and working correctly, like make a new PHP file and put in <?php session_start(); print_r($_SESSION); ?> 如果这不起作用,你应该调试你的会话是init并正常工作,比如制作一个新的PHP文件并放入<?php session_start(); print_r($_SESSION); ?> <?php session_start(); print_r($_SESSION); ?>

You need to call session_start() function before getting value of session, so, you need to put: 您需要在获取会话值之前调用session_start()函数,因此,您需要将:

session_start();

At the top of that file. 在该文件的顶部。

Also, <script type="text/javascript" src="/file.php"></script> is for JavaScript file, not external style sheet, and last note is you can print the value without single quotes: 此外, <script type="text/javascript" src="/file.php"></script>用于JavaScript文件,而不是外部样式表,最后一点是您可以打印没有单引号的值:

color: #<?php echo $_SESSION['colorOne']; ?>

Your file needs to be processed by PHP when it gets requested. 请求时,PHP需要处理您的文件。 When you are on Apache you need to add 当你在Apache上时,你需要添加

AddType application/x-httpd-php .MYFILEEXTENSION

to your .htaccess file. 到您的.htaccess文件。 im not quite sure about nginx. 我不太确定nginx。

As a general idea, i've allways done this in the index.php file. 总的来说,我总是在index.php文件中完成这个。 Just print something into a global variable like 只需将某些内容打印到全局变量中即可

window.phpTransitionVariables = { ... };

with a script tag like this 用这样的脚本标签

<script type="text/javascript">
    <? //print my php variables
</script>

write

<?php
header('content-type: text/css');
?>

on begin from the css file with php extension 从php扩展的css文件开始

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

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