Using PHP in a .JS file?

So, I'm trying to use PHP in a .js file, that's what I still have.

.htaccess (any * .api.js will be processed as PHP)

<FilesMatch "^.*?api.*?$">
SetHandler php54-script
</FilesMatch>

map.api.js

<?php
header("Content-type: application/javascript");
//my php here
?>

//my javascript here

.php files include

<script type="text/javascript" src="map.api.js"></script>

For some reason this does not work, and after much research, I cannot find a solution.

In the developer’s chrome tools, I get an error message Uncaught SyntaxError: Unexpected token <- quite understandably, he does not expect <?phpat the top of the file map.api.js.

Has anyone else tried using PHP in a .js file before? If there is a better solution I would like to know, since I cannot find much on Google.

+4
source share
3 answers

php javascript.

map.api.js

<?php
header("Content-type: application/javascript");
//my php here
?>
//my javascript here

HTML:

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

php, mod_rewrite (Apache):

RewriteEngine on
RewriteRule ^map.api.js$ map.api.php
+5

PHP .api.js. .php , Content-Type.

, :

<?php
    header("Content-Type: application/javasctipt);
    // code...
?>

alert("This is JS");

HTML :

<script src="/map.api.php"></script>

, JS- PHP , - :

<script src="/map.api.php?feature=1"></script>

PHP:

<?php
    header("Content-Type: application/javasctipt);
?>

alert("This is JS");

<?php
    if ($_GET["feature"] == "1") {
        echo "alert('Cool feature imported');";
    }
?>
+2

.

PHP- dotJS.

.htaccess

<FilesMatch "\bapi\b">
SetHandler php54-script
</FilesMatch>

, .htaccess Apache:

<Directory /your/path>
AllowOverride All
Order deny,allow
Deny from all
Satisfy all
</Directory>
+1

Source: https://habr.com/ru/post/1626174/


All Articles