我正在使用Codeigntier,我在我的视图文件中有以下下拉列表,其中填充了一系列主题。
<?php echo form_dropdown('subject1', $dropdown_subjects,'',
'class="required" id="subject1"'); ?>
现在当任何人从上面的下拉列表中选择任何值时,我想使用jquery将值发送到我的控制器并在下表( SELECT teacherid from table3 WHERE subjectid=$subjectid)
中查询以获取teacherid,以便我可以填充teacherid列表另一个下拉选择。如果任何用户从第一个下拉列表中更改了他的选择,我希望第二个下拉列表的值也改变
表名:table3
subjectid teacherid
1 1001
2 1003
所以底线是我想根据另一个下拉列表填充下拉列表。我已经找到了关于这个主题的几个教程,但我无法理解那些(我知道我很愚蠢)。
如果我想实现这一目标,请您告诉我我的视图和控制器应该是什么样的?
谢谢:)
嗨,这就是我的控制器和视图文件的样子:
我的控制器
$id= $this->input->post('subject_id'); //receiving the ajax post from view
$this->db->select('teachername,teacherid');
$this->db->from('subject_teacher');
$this->db->join('teacher', 'teacher.teacherid = subject_teacher.teacherid');
$this->db->where('subjectid',$id);
$records = $this->db->get('');
$data=array();
$data[''] = 'Select';
foreach ($records->result() as $row)
{
$data[$row->teacherid] = $row->teachername;
}
return ($data); // I need help here... How to send the data as json?
我的观点:
<script>
$(function(){
$("#subject").change(function(){
$.ajax({
url: "<?echo base_url();?>mycontroller/function",
data: {subject_id: $(this).val()},
type: "post",
success: function(msg){
$("#teacher").html(); // I need help here...how do I get the value from controller and append to my another dropdown named teacher?
})
})
}); // function ends here
</script>
<?php echo form_dropdown('subject1', $dropdown_subjects,'',
'class="required" id="subject1"'); ?>
<select name="teacher" id="teacher">
<option value="">Select</option>
</select>
请为我的视图和控制器进行必要的更改。
提前致谢:)
答案 0 :(得分:3)
您可以使用jquery ajax执行此操作。首先将 subject_id 发布到ajax页面,ajax页面将返回组合框中的teacher列表,然后在第一页中填充结果。
$("#subject").change(function(){
$.ajax({
url: "your-ajax-page-url",
data: {subject_id: $(this).val()},
type: "post",
success: function(msg){
$("#teacher").html();
})
})
这是已编辑的控制器
$id= $this->input->post('subject_id'); //receiving the ajax post from view
$this->db->select('teachername,teacherid');
$this->db->from('subject_teacher');
$this->db->join('teacher', 'teacher.teacherid = subject_teacher.teacherid');
$this->db->where('subjectid',$id);
$records = $this->db->get('');
$output = null;
foreach ($records->result() as $row)
{
$output .= "<option value='".$row->teacherid."'>".$row->teachername."</option>";
}
echo $output; // HTML example
答案 1 :(得分:0)
你必须在你的控制器中创建一个能够填充数据的函数,但不是输出你的视图,你必须把它放在像这样的var中
$outout = $this->load->view('myselect_output',$data,TRUE);
然后在主视图中,您将不得不使用jquery或任何其他js库来操作DOM。