我正在使用一个 phtml 文件,该文件需要从托管在同一服务器上的 javscript 文件中读取静态 json 对象。
我在实际访问 JSON 对象时遇到问题,以便我可以操作它并让它显示在屏幕上(最终使用适当的锚点等)
这是我尝试访问对象的方式,但 php 对我来说相对较新。
<?php
require_once '/path/to/my/resource.js';
$json = ns.path.VARIABLE;
?>
<?php echo $json; ?>
我的javascript文件位于/path/to/my/resource.js:
ns.path.VARIABLE = {
Part1: {
'Key1': 'Value1',
'Key2': 'Value2'
}
Part2: {
'Key1': 'Value1',
'Key2': 'Value2'
}
}
我没有成功。我可以说 js 文件包含在对浏览器的响应中,但我无法通过 VARIABLE Json 对象。
知道如何访问 JSON,然后我将解析并呈现给浏览器吗?
是不可能的。PHP 在服务器上运行,而 JS 在客户端上运行。最好的机会是从文件中删除ns.path.VARIABLE
部分,并通过在其上使用file_get_contents()
将其读取为实际的 JSON 文件
例
资源.json
{
Part1: {
'Key1': 'Value1',
'Key2': 'Value2'
}
Part2: {
'Key1': 'Value1',
'Key2': 'Value2'
}
}
PHP代码
<?php
$json = json_parse(file_get_contents('resource.json'));
就这么简单!
编辑
在发布的特定代码上,您可以执行以下操作,但它似乎不安全或灵活:
// Load the file as a string
$js_string = file_get_contents('resource.js');
// Remove the namespace part so that you can parse it as a JSON string
$js_string = str_replace('ns.path.VARIABLE =', '', $js_string);
// Convert it to an associative array you can use in PHP
$array = json_decode($js_string);
这里有一些问题。首先,你所谓的JSON实际上根本不是JSON。通过像 http://jsonlint.com/这样的工具运行它,你会看到。正确的 JSON 应如下所示:
{
"Part1": {
"Key1": "Value1",
"Key2": "Value2"
},
"Part2": {
"Key1": "Value1",
"Key2": "Value2"
}
}
此外,你混淆了PHP和Javascript。正如其他人已经说过的,JS在浏览器中运行,PHP在服务器上运行。你不能按照你尝试的方式混合它们。@Loupax提供的答案基本上是正确的,但我相信可以更容易地完成。它不需要你包含的文件是JSON,一个普通的JS对象就可以了。像这样:
<script type="text/javascript">
var ns = {
path: {}
};
<?= include '/path/to/my/resource.js'; // this will just paste the contents of that file inside this script block before sending it to the browser ?>;
// here you can use that object
console.log(ns.path.VARIABLE.Part1.Key1);
</script>
请注意,我首先必须创建包含 path
对象的 ns
对象,以便能够为其分配VARIABLE
对象。这也假设您保持所谓的JSON文件不变,除了第1部分和第2部分之间缺少逗号
很难从您的代码片段中分辨出来,但我认为您可能只需将其称为variable
就可以侥幸逃脱,然后您就不必执行第一步。还有一点建议,在命名变量时尽量保持一致。普遍的共识是类以大写字母开头,函数和变量以小写字母开头,常量都是大写的。您不必遵循这些规则,而只需尝试坚持您的选择即可。这将使编码和调试变得更加容易。
作为结论,我的代码可能看起来像这样:
文件/到/包含.js
{
part1: {
key1: 'Value1',
key2: 'Value2'
},
part2: {
key1: 'Value1',
key2: 'Value2'
}
}
view.phtml
<script type="text/javascript">
var paths = <?= include 'file/to/include.js'; ?>;
console.log(paths.part1.key1);
</script>