【发布时间】: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