codeigniter JSON [英] codeigniter JSON
问题描述
Hello im using codeigniter,然后我回应我的控制器中的数据库的输出,然后在我的视图文件中我这样做:
Hello im using codeigniter and then i echo out my output from the database in my controller and then in my view file i do this:
<script type="text/javascript">
$.getJSON('ajax/forumThreads', function(data) {
alert(data.overskrift);
});
</script>
但不显示任何内容:S
but it dont show anything :S
我的模型文件
function forumList()
{
$this->db->select('overskrift', 'indhold', 'brugernavn', 'dato');
$this->db->order_by('id', 'desc');
$forum_list = $this->db->get('forum_traad');
if($forum_list->num_rows() > 0)
{
return $forum_list->result();
} else {
return false;
}
}
我的控制器
function forumThreads() {
$this->load->model('ajax_model');
$data['forum_list'] = $this->ajax_model->forumList();
if ($data['forum_list'] === true)
{
echo json_encode($data['forum_list']);
$this->load->view('includes/footer', $data);
} else {
return false;
}
}
推荐答案
$ forum_list-> result()
返回结果数组。
你只需要1行,使用 $ forum_list-> row()
,否则在javascript中,你需要循环遍历所有行。
If you only want 1 row, use $forum_list->row()
, otherwise in the javascript, you'll need to loop through all the rows.
$.each(data, function(i,v){
alert(v.overskrift);
});
编辑:输出JSON时,不要打印前后的任何内容。您需要删除 json_encode $后面的
$ this-> load-> view('includes / footer',$ data);
c $ c>。
When outputting JSON, do not print anything before or after. You need to remove $this->load->view('includes/footer', $data);
after the json_encode
. Also, controllers don't return anything.
编辑2:取代 if($ data ['forum_list'] === true) code>与
if($ data ['forum_list']!== false)
。 ===
比较类型,数组不是布尔值。
EDIT 2: Replace if ($data['forum_list'] === true)
with if ($data['forum_list'] !== false)
. The ===
compares type, and an array is not a boolean.
这篇关于codeigniter JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!