【问题标题】:php encoded json to template and javascriptphp将json编码为模板和javascript
【发布时间】:2015-04-21 14:35:16
【问题描述】:

我正在使用 Codeigniter 和 Smarty(模板引擎),因此使用模板。

我有一个方法可以调用具有所有 html、css 和 js 功能的模板:

public function index()
{
    //dashboard text
    $this->data['title'] = 'Dashboard';
    $this->data['subtitle'] = 'feeds, users, and more';

    //load the donut graph data
    $fbyg = $this->feed_model->countFeedsByGroups();
    echo json_encode($fbyg);

    //parses the dashboard template
    $this->smartyci->display('dashboard.tpl', $this->data);
}

问题是我需要将一些信息发送到绑定到我的 dashboard.tpl 的 js 文件之一,以便呈现图形。

所以我知道我必须将 php 数组编码为 jSon 对象并将其发送到模板。但是,当我不仅要发送和回显 json 并且我必须显示我的模板发送其他信息时,我该怎么做?

另一个问题是,我如何接收 json 并获取数据?我正在尝试,目前没有结果:

来自我的dashboard.tpl:

    <script src="{site_url()}application/views/js/test.js"></script>
    <script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script>

来自 test.js:

$.getJSON('admin.php', function(data) {
    console.log(data.vgro_name);
});    

【问题讨论】:

  • 不要使用echo,而是返回字符串,这样你就可以随时使用它了。
  • 你的意思是我应该把它放在像 $this->data['jsondata'] = json_encode($fbyg) 这样的变量中?如何在函数中访问这些数据?
  • 删除echo json_encode($fbyg); 并在函数末尾添加return json_encode($fbyg);,这样您就可以在echo index()$data = index(); 中随意使用它。

标签: javascript php ajax json codeigniter


【解决方案1】:

你可以这样设置

$this->data['fbyg'] = json_encode($fbyg);

然后在你的javascript中做

var yourVar = <?php echo $fbyg ?>;

更简洁的解决方案是对将返回类似内容的函数进行 ajax 调用

$fbyg = $this->feed_model->countFeedsByGroups();
echo json_encode($fbyg);

页面加载后。

编辑 jQuery ajax 获取:

$.ajax({
  type: "GET",
  url: "urlToYourFunction",
  success: function(data){
     var yourVar = data;
  }
});

我只使用 angularjs 和 jquery 发出过 get 和 post 请求,但这里是另一个 stackoverflow 帖子,详细说明了如何使用常规 javascript 进行此操作:

https://stackoverflow.com/a/18078705/3739551

我希望这会有所帮助!

【讨论】:

  • 我不想使用 ;因为我没有在 php 文件中加载 javascript。所以我需要从 php 文件外部访问该变量
  • 然后你会想要做 ajax 调用 :)
  • 我该怎么做?我找不到解决方案
  • 我用一个示例和一个指向常规 javascript 方式的链接为您编辑了我的答案。希望对您有所帮助!
  • 即使我使用了你提到的ajax函数,我也无法在同一个函数中发送模板和json对象
猜你喜欢
  • 2012-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-11
相关资源
最近更新 更多