如果你想真正走出去,你可以让 HTML 页面请求一个 .js 文件,加上他们的 session-id 或其他一些他们是谁的指标,将 .js 调用作为 PHP 调用来操作,动态构建JS 基于他们的会话要求,然后将其作为 .js 文件类型输出回浏览器。
但这是很多工作。
如果您想要味道更淡的东西,请让 PHP 在文件末尾转储 JSON 字符串:
var cfg_string = "{\"username\":\"Norguard\", \"new_messages\":[......]}"; // client
$cfg_obj = array(); // whole lot o'PHP
$json_encoded_cfg = json_encode($cfg_obj);
echo "var cfg_string = {$json_encoded_cfg};" //server-side
然后在客户端解析它以增加安全性......
...或者直接在模板中创建一个地图:
$cfg_string = "var dataMap = {";
foreach ($cfg_obj as $key => $val) {
// print key:val all pretty-like,
// handle commas (ie: no trailing comma at the end), indent with tabs or spaces
// if you want, count the number of items so that the object closes ({})
// without any newline operator, if there are no config settings
}
echo $cfg_string;
Both of these are clean and unobtrusive and keep everything separate.
The config data/text can go right above whatever your init/loading code is going to be, and be passed in as a parameter to that init-logic.