我意识到这可以用ajax完成。只想通过codeigniter
查看是否可行我想要一个ajax click事件来触发codeigniter将数据发送到当前加载的视图。在我的示例中,我想填充一个空的ul,其中包含从数据库中提取的名称。
//SETUP
//html. This file is views/index.php. This is an example of what I want to do
<ul>
<?php
foreach ($names as $name)
{
echo "<li>".$name."</li>";
}
?>
</ul>
//ajax
$(".button").click(function() {
$.ajax({
method: 'GET',
datatype: 'jsonp',
url: 'localhost/tableseating/tables/load_names'
});
});
//controller
public function load_names()
{
$names = $this->My_model->load_names();
//this is the current view already
$this->load->view('index', $names);
}
//model
public function load_names()
{
$q = "SELECT first_name FROM `users`";
$query = $this->db->query($q);
$result = $query->result();
return $result;
}
答案 0 :(得分:0)
你改变控制器
不是ajax
//controller
public function load_names()
{
$data['names'] = $this->My_model->load_names();
//this is the current view already
$this->load->view('index', $data);
}
使用ajax
//controller
public function load_names()
{
$names = $this->My_model->load_names();
//this is the current view already
$li = '';
foreach($names as $row)
{
$li .= '<li>'.$row->name.'</li>';
}
$data['names'] = $li;
$this->load->view('index', $data);
}
//ajax
$(".button").click(function() {
$.ajax({
method: 'GET',
datatype: 'html',
url: 'localhost/tableseating/tables/load_names',
success: function(data)
{
$('#data').html(data);
}
});
});
// view
<ul id="data">
</ul>