使用PHP include函数将JSON文件添加到JS中

Add JSON file to JS with the PHP include function

本文关键字:添加 JS 文件 JSON PHP include 函数 使用      更新时间:2023-09-26

我曾经做过以下操作,将JSON文件的内容添加到我的JS代码中,但由于我更改了web主机,我收到了以下错误:"Unaught SyntaxError:Unexpected token<"

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

我哪里错了?

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

尝试在.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文件。

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

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

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