我有一个Switches.js
javascript文件,如下所示:
//GLOBAL switches
//Change the values accordingly
var SWITCHES = {
uber: true, //Uber
social: true, //Social media pulgins
g_charts: true, //Google Charts
g_captcha: true, //Google Captcha
g_analytics: true, //Google Analytics
data_base: true, //Inserts user input data into DataBase
print: true, //Print option
pdf: true, //Download PDF report option
https: true //true for https, false for http
};
此JS文件存储在我的服务器中。
有没有办法将该对象和其中一个属性转换为php变量?我认为应该围绕php函数file_get_contents
和json_decode
,但我如何考虑JS文件中的注释以及特别是变量SWITCHES
?
$file_content = file_get_contents("Switches.js");
//some stuff
$http_switch = $SWITCHES[https];
AJAX和jQuery是一个选项,因为这是纯服务器端运行。
答案 0 :(得分:2)
由于Switches.js
是JavaScript而不是JSON,因此您无法使用json_decode()
。相反,您应该将其转换为JSON并在客户端和服务器端解码/解析它:
在PHP中,您可以:
$data = file_get_contents("Switches.json");
$switches = json_decode($data);
然后客户端通过AJAX获取并解析:
$.get("/Switches.json", function (data) {
var switches = JSON.parse(data)
})
您的Switches.json
文件将是(JSON文件必须没有注释):
{
"uber": true,
"social": true,
"g_charts": true,
"g_captcha": true,
"g_analytics": true,
"data_base": true,
"print": true,
"pdf": true,
"https": true
}