我正在尝试在我的视图中打印json_encode。但它总是显示为json对象。我想在html格式的输出中打印下面的对象。我只是为分页结果实现了一个像更多按钮的推特。有人可以帮助我。
这是我的控制器:
function get_results($offset)
{
$this->load->model('my_model');
$this->data['latest_messages'] = $this->my_model->searchresult($offset);
$this->output->set_header('Content-Type: application/json; charset=utf-8');
echo '<script> var data = ' . json_encode($this->data['latest_messages']). ' </script>';
}
以下是我的观点:
<script type="text/javascript">
google.load("jquery", "1.10.1");
</script>
<script type="text/javascript">
$(document).ready(function(){
var num_messages = <?=$num_messages?>;
var loaded_messages = 0;
$("#more_button").click(function(){
loaded_messages += 10;
$.get("<?php echo $base_url;?>" + "controller/get_results/" + loaded_messages, function(data){
$("#main_content").append(data);
});
if(loaded_messages >= num_messages - 10)
{
$("#more_button").hide();
}
})
})
</script>
<link rel="stylesheet" href="<?=base_url();?>css/main.css" type="text/css" />
</head>
<body>
<?php $this->load->view('includes/topbar'); ?>
<?php $this->load->view('includes/menu'); ?>
<?php $this->load->view('includes/left'); ?>
<div id="contentwrap">
<div id="content">
<div id="main_content">
<?php
foreach($this->data['latest_messages'] as $message)
{
echo $message->email . ' - ' . '<br />';
}
?>
</div>
<div id="more_button">
More
</div>
</div>
</div>
<?php $this->load->view('includes/right'); ?>
<?php $this->load->view('includes/foot'); ?>
当我点击更多链接时,结果正常加载,但我希望以一个漂亮的格式化输出而不是json对象显示结果,如下所示
[
{" id":"11"," group_fk":"1"," email":"test1@gmail.com"," username":"test1"},
{" id":"12"," group_fk":"1"," email":"test2@gmail.com"," username":"test2"},
{" id":"13"," group_fk":"1"," email":"test3@gmail.com"," username":"test3",},
]
答案 0 :(得分:0)
好的,所以你以json格式获得结果。您只需要在ajax返回处理程序中操作这些结果,然后将它们附加到div:
$.get("<?php echo $base_url;?>" + "controller/get_results/" + loaded_messages,
function(data){
var data = JSON.parse(data);
var output = "";
for (var i = 0; i < data.length; i++) {
output += data[i].email + ' - <br />';
}
$("#main_content").append(output);
}
);