【问题标题】:Using PHP in .JS file?在 .JS 文件中使用 PHP?
【发布时间】:2023-04-10 03:28:01
【问题描述】:

所以我尝试在 .js 文件中使用 PHP,这就是我目前所拥有的。

.htaccess(任何 *.api.js 都将作为 PHP 处理)

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

ma​​p.api.js

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

//my javascript here

.php 文件全部包含

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

由于某种原因,这不起作用,经过大量研究,我找不到解决方案。

在 chrome 开发者工具中,我收到了一个错误,Uncaught SyntaxError: Unexpected token &lt; - 不言自明,它不期望 &lt;?php 位于 map.api.js 文件的顶部。

这里还有其他人尝试过在 .js 文件中使用 PHP 吗?如果有更好的解决方案,我想知道,因为我在 Google 上找不到太多信息。

【问题讨论】:

  • 我试图避免将 1000 多行 javascript 放在我的 HTML 文件的顶部,所以我想知道是否有解决方案来解决我尝试这样做的方式。
  • 你的正则表达式看起来很糟糕。尝试\bapi\b 而不是^.*?api.*?$;

标签: javascript php .htaccess


【解决方案1】:

您实际上不需要将 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');";
    }
?>

【讨论】:

  • 从 .htaccess 中删除了 PHP 处理程序并使用了 Take 的解决方案。现在它可以工作了,谢谢 Marco!
【解决方案2】:

Take 的响应是最佳实践。

如果你真的想在 dotJS 文件中执行 PHP 代码。

.htaccess

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

并确保在 Apache 配置中允许 .htaccess:

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

【讨论】:

    【解决方案3】:

    创建一个带有 php 扩展名的文件,并将其作为 javascript 包含在您的网站中。

    ma​​p.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
    

    【讨论】:

    • 由于某种原因,在将 map.api.js 重命名为 map.api.php(并在我的 html/php 文件中更新它)后,我仍然收到 Uncaught SyntaxError: Unexpected token &lt; 错误
    • 我从 .htaccess 文件中删除了 PHP 处理程序,现在它可以工作了,谢谢!
    猜你喜欢
    • 1970-01-01
    • 2012-11-25
    • 1970-01-01
    • 2010-10-29
    • 1970-01-01
    • 2016-09-13
    • 1970-01-01
    • 2013-12-18
    • 1970-01-01
    相关资源
    最近更新 更多