javascript 代码点火器 JSON
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4616916/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
codeigniter JSON
提问by ole
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:
你好,我使用 codeigniter,然后我从控制器中的数据库中输出我的输出,然后在我的视图文件中我这样做:
<script type="text/javascript">
$.getJSON('ajax/forumThreads', function(data) {
alert(data.overskrift);
});
</script>
but it dont show anything :S
但它没有显示任何内容:S
my model file
我的模型文件
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;
}
}
my controller
我的控制器
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;
}
}
回答by Rocket Hazmat
$forum_list->result()returns an array of results.
$forum_list->result()返回结果数组。
If you only want 1 row, use $forum_list->row(), otherwise in the javascript, you'll need to loop through all the rows.
如果您只需要 1 行,请使用$forum_list->row(),否则在 javascript 中,您需要遍历所有行。
$.each(data, function(i,v){
alert(v.overskrift);
});
EDIT: 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.
编辑:输出 JSON 时,不要在之前或之后打印任何内容。您需要$this->load->view('includes/footer', $data);在json_encode. 此外,控制器不返回任何东西。
EDIT 2: Replace if ($data['forum_list'] === true)with if ($data['forum_list'] !== false). The ===compares type, and an array is not a boolean.
编辑 2:替换if ($data['forum_list'] === true)为if ($data['forum_list'] !== false). 的===比较类型,和阵列是不是一个布尔值。
回答by fire
Model:
模型:
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_array();
} else {
return false;
}
}
Controller:
控制器:
function forumThreads() {
$this->load->model('ajax_model');
$data['forum_list'] = $this->ajax_model->forumList();
if ($data['forum_list'] !== false) {
echo json_encode($data['forum_list']);
}
}
回答by Diablo
Try this:
试试这个:
//works only with php 5.3
echo json_encode($data['forum_list'], JSON_FORCE_OBJECT);

