Home > Article > Backend Development > How can I access PHP variables from external JavaScript files?
Accessing PHP Variables from External JavaScript Files
Accessing PHP variables from inline JavaScript code is straightforward using PHP's echo statement. However, when using external JavaScript files, a different approach is necessary.
Inserting PHP Values into JavaScript Code
The solution lies in inserting the PHP variable values into the JavaScript code at the time of generating the page. This can be achieved using PHP's echo statement within the HTML:
<?php $color = "Red"; ?> <script type="text/javascript">var color = "<?php echo $color; ?>";</script> <script type="text/javascript" src="externaljs.js"></script>
Accessing PHP Variables from External JavaScript File
In the external JavaScript file (externaljs.js):
alert("color: " + color);
Using this method, the external JavaScript file can access the PHP variable value by referencing the variable name that was inserted into the code using echo.
The above is the detailed content of How can I access PHP variables from external JavaScript files?. For more information, please follow other related articles on the PHP Chinese website!