我加载了 View ,我想通过 ajax JSON 请求显示从数据库中获取的记录。但它没有显示记录。
这是我的 View 代码
<div class="col-md-6" id="hodm_table">
<table class="table table-striped table-hover table-responsive">
<thead>
<tr>
<th>Task Name</th>
<th>Director</th>
<th>Duration</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<?php foreach($result as $hodm) { ?>
<tr>
<td><?php echo $hodm->t_name;?></td>
<td><?php echo $hodm->director;?></td>
<td><?php echo $hodm->duration;?></td>
<td><?php echo $hodm->status;?></td>
<?php } ?>
</tbody>
</table>
</div>
</div>
<script type='text/javascript' language='javascript'>
$(document).ready(function(){
$.ajax({
url:"<?php echo base_url();?>digital/dashboard/dig_short_hodm_table",
type: 'POST',
dataType: 'JSON',
success:function (data) {
$('#hodm_table').html(data);
}
});
event.preventDefault();
});
</script>
这是我的模型
public function get_hodm()
{
return $this->db->get("hodm");
}
这是我的 Controller
public function dig_short_hodm_table(){
$data['result']=$this->pojo->get_hodm();
return json_encode($data);
}
当我加载我的页面然后它显示错误
Message: Undefined variable: result
我想在加载 View 时从数据库中获取记录并显示在 View 表中。
最佳答案
更新您的模型:
public function get_hodm(){
return $this->db->get("hodm")->result();
}
你的 Controller :
public function dig_short_hodm_table(){
$result_html = '';
$result_set = $this->pojo->get_hodm();
foreach($result_set as $result) {
$result_html .= '
<tr>
<td>' . $result->t_name . '</td>
<td>' . $result->director . '</td>
<td>' . $result->duration . '</td>
<td>' . $result->status . '</td>
</tr>';
}
echo json_encode($result_html);
}
最后是你的看法:
<div class="col-md-6" id="hodm_table">
<table class="table table-striped table-hover table-responsive">
<thead>
<tr>
<th>Task Name</th>
<th>Director</th>
<th>Duration</th>
<th>Status</th>
</tr>
</thead>
<tbody id="hodm_results">
</tbody>
</table>
</div>
<script type='text/javascript' language='javascript'>
$(document).ready(function(){
$.ajax({
url:"<?php echo base_url();?>digital/dashboard/dig_short_hodm_table",
type: 'POST',
dataType: 'JSON',
success:function (data) {
$('#hodm_results').html(data);
}
});
event.preventDefault();
});
</script>
关于php - codeigniter 返回从 Controller 获取数据以通过 Ajax 请求查看,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43339090/