我使用的 phtml 文件需要从同一服务器上托管的 javscript 文件读取静态 json 对象。
我在实际访问 JSON 对象时遇到了麻烦,以便我可以操作它并将其显示在屏幕上(最终使用适当的 anchor 等)
这是我尝试访问该对象的方式,但 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,然后我将解析该 JSON 并将其呈现给浏览器吗?
最佳答案
这是不可能的。 PHP运行在服务器上,而JS运行在客户端上。最好的机会是从文件中删除 ns.path.VARIABLE
部分,并使用 file_get_contents()
将其作为实际的 JSON 文件读取
示例
resource.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);
关于javascript - 从 phtml 文件访问 Javascript 命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26981158/