A better approach is to think of Javascript as PHP code.
The main steps:
- Create a .htaccess file that redirects all JS files (.js) to the index file.
- In this index file, the JS file is loaded as a PHP module (
require "script/$file" ) - Modify all JS files as needed. You can now embed the PHP code.
For example, add this line to your .htaccess:
RewriteRule \.js$ index.php
In your index.php file, put something like this:
// Process special JS files $requested = empty($_SERVER['REQUEST_URI']) ? "" : $_SERVER['REQUEST_URI']; $filename = get_filename($requested); if (file_ends_with($requested, '.js')) { require("www/script/$filename.php"); exit; }
And finally, in the file.js.php file, you can embed PHP, use the GET and POST options, etc.:
<?php header("Content-type: application/x-javascript"); ?> var url = "<?php echo $url ?>"; var params = "<?php echo $params ?>"; function xxxx().... ....
In addition, the trick to skipping the file cache is to add a random number as a javascript parameter:
<script type="text/javascript" src="scripts/file.js?a=<?php echo rand() ?>"></script>
Also, as stated in the comment, if your web server does not allow changing .htaccess , you can simply request the PHP file directly:
<script type="text/javascript" src="file.php"></script>
source share