javascript - 从 phtml 文件访问 Javascript 命名空间

标签 javascript php json require

我使用的 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/

相关文章:

ajax - 何时将 Ajax 与 Json 用于 Javascript 事件?

ruby-on-rails - Ruby API 响应为小驼峰式

javascript - get 函数无法与 JSON 字符串中的本地存储正常工作

javascript - 为什么我的两个 div 总是紧挨着?

javascript - 输入类型 ="date"设置默认值到今天

javascript - 如何获取服务器中的用户列表

php - ListView 重复值

PHP异常 fatal error "name is already in use"

php - 为什么会出现mime类型与firefox、chrome不一致的问题?

javascript - 用 Jest 测试 Observer 完成事件?