我有2张桌子 - 汽车制造商和汽车模型。我从数据库中提取数据。当我点击第一个表格中的制作人时,我希望第二个表格只显示来自该制作人的汽车。我尝试使用ajax,但ajax请求似乎没有覆盖$ DBcontent变量,因此第二个表不会被过滤。 但是当我使用console.log(数据)时;在成功的Ajax上它显示正确的记录。 我误会了什么吗?我省略了SQL查询,因为它们简单且不相关。
控制器CarListController.php:
<?php
class CarListController extends CI_Controller
{
public function index()
{
$this->load->model('OutputFromDatabaseModel');
$this->load->helper(array('form', 'url'));
$query = $this->OutputFromDatabaseModel->getProducers();
$DBcontent['PROD'] = $query;
$query = $this->OutputFromDatabaseModel->getCars(); // fill with all Cars first
$DBcontent['CARS'] = $query;
$this->load->view('CarListView', $DBcontent);
}
}
?>
查看CarListView.php:
<script>
var URL = "(myURL)/index.php/Process/FilterCars";
$(document).ready(function()
{
$(".test").click(function(e) //row from Producer table
{
$ID = this.id;
$.ajax({
type: "POST",
url: URL,
data: {id:$ID},
dataType : "json",
});
showModels = true;
if (showModels) // only show the car models table when clicked on a producer
{
document.getElementById("modelTable").style.display="";
}
});
});
</script>
<body>
<div class="col-xs-2">
<table id="producerTable" class="table table-striped table-bordered table-hover table-responsive">
<tr><td><strong>Producer</strong></td></tr>
<?php foreach($PROD as $producer){?>
<tr class="test" id="<?=$producer->ProducerID?>"><td><?=$producer->ProducerName;?></td></tr>
<?php }?>
</table>
</div>
<div class="col-xs-3">
<table id="modelTable" style="display:none" class="table table-striped table-bordered table-hover table-responsive">
<tr><td><strong>Car Model</strong></td></tr>
<?php foreach($CARS as $car){?>
<tr id="<?=$car->CarId?>"><td><?=$car->Model;?></td></tr>
<?php }?>
</table>
</div>
</body>
AjaxProcess Process.php:
<?php
class Process extends CI_Controller
{
public function index(){
$this->load->view('CarListView', $DBcontent); //tried to put it everywhere
}
function FilterCars(){
$this->load->model('OutputFromDatabaseModel');
$this->load->helper(array('form', 'url'));
$ProducerID = $this->input->post('id');
$query = $this->OutputFromDatabaseModel->getCarsOfProducer($ProducerID); //filtered by Producer
$DBcontent['CARS'] = $query;
}
}
?>
如何使用更新的$ DBcontent变量启动View?如果采用错误的方法,有哪些替代方案。
答案 0 :(得分:0)
您的第二张桌子可能仍然显示所有车辆,因为您的ajax请求没有做任何事情,它只是将数据发布到服务器,您没有使用它返回的数据。你只需设置&#34; modelTable&#34;在ajax调用后可见。
请参阅Jquery Ajax中的success
函数http://api.jquery.com/jquery.ajax/
$(".test").click(function(e) //row from Producer table
{
$ID = this.id;
$.ajax({
type: "POST",
url: URL,
data: {id:$ID},
dataType : "json",
success:function(data){ // function to call when the ajax call sucessful
// i simply replace the content of the table with the response with ajax,
//you can use the data to create html here and append it into the table.
$('#modelTable').html(data);
}
});
}