使用 PHP 包含函数将 JSON 文件添加到 JS

Add JSON file to JS with the PHP include function

我曾经执行以下操作将 JSON 文件的内容添加到我的 JS 代码中,但是由于我更改了我的网络主机,我收到此错误:"Uncaught SyntaxError: Unexpected token <"

var someVar = <?php include 'someJsonFile.geojson'; ?>;

我哪里错了?

可能您以前的虚拟主机是通过 php 解释器 运行 .js 文件。

最快的解决方案是将 javascript 包含在脚本标记内的 php 文件中。

...
<head>
   <script type="text/javascript">
      var someVar = <?php include 'someJsonFile.geojson'; ?>;
   </script>
</head>
...

一个快速解决方法可能是在您的 js 文件所在的目录中修改现有的 .htaccess 文件(或创建一个新的 .htaccess 文件)。

尝试将以下行之一添加到 .htaccess 文件中:

AddHandler x-httpd-php .html .htm .js
AddHandler php-script .php .html .htm .js
AddHandler php5-script .php .html .htm .js
AddType application/x-httpd-php .htm .js
AddType application/x-httpd-php .html .js

注意到末尾的“.js”了吗?这将指示服务器通过PHP.

处理js文件