简体   繁体   中英

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. I've tried making the .js into a php and adding an echo but it doesn't work.

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

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

Everything works perfect when I replace the php with an actual color (#FFFFFF). I run into problems when I add the php.

PHP can emulate any content you'd like, even Images, PDF and Office files.

First, don't confuse Javascript with CSS.

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

At the beginning of the file.php , make sure you start the session:

<?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); ?> <?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();

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:

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

Your file needs to be processed by PHP when it gets requested. When you are on Apache you need to add

AddType application/x-httpd-php .MYFILEEXTENSION

to your .htaccess file. im not quite sure about nginx.

As a general idea, i've allways done this in the index.php file. 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

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