我有一个视图文件
<select name="tournaments" id ="tournaments" class="form-control">
<?php foreach ($tournaments as $tournament): ?>
<option value="<?php echo $tournament->TournamentID ?>"><?php echo $tournament->TournamentName ?></option>
<?php endforeach ?>
</select>
脚本
<script type="text/javascript">
$(document).ready(function(){
var initial_target_html = '<option value="">Please select a Tournament...</option>'; //Initial prompt for target select
$('#matches').html(initial_target_html);
$("#tournaments").change(function(e){
e.preventDefault();
var data = ($("#tournaments").val());
$('#matches').html('<option value="">Loading...</option>');
$.ajax({
type:"POST",
dataType: 'json',
url:"<?php echo base_url('admin/dashboard/update_match_box') ?>",
data: {tournament:data},
success: function(data) {
}
});
});
});
</script>
控制器功能
public function update_match_box()
{
$sql = "Some query"
$query = $this->db->query($sql);
$json= $query->result();
$this->output->set_content_type('application/json')
->set_output(json_encode($json));
}
控制器文件将返回多行,我需要在ajax成功事件中捕获并相应地更新第二个选择框,我怎么想这样做?
答案 0 :(得分:0)
你应该看看form_helper文件,它有很多有用的函数来构建表单输入,你所要做的就是加载这个帮助器: 在application / config / autoload.php中,转到“helper”并添加帮助名称如下:
$autoload['helper'] = array('form');
接下来,转到您的视图文件并进行更改:
<select name="tournaments" id ="tournaments" class="form-control">
<?php foreach ($tournaments as $tournament): ?>
<option value="<?php echo $tournament->TournamentID ?>"><?php echo $tournament->TournamentName ?></option>
<?php endforeach ?>
</select>
到此:
<?php
// $tournaments must me an array, use ->result_array() instead of ->result_object()
$tournaments = array_column($tournaments, 'TournamentName', 'TournamentID');
echo form_dropdown('tournaments', $tournaments, '', 'id="tournaments" class="form-control")
?>
对于成功的回调函数,您可以使用$ .each或仅使用for循环来提取每个元素并为select输入创建选项:
$.ajax({
type:"POST",
dataType: 'json',
url:"<?php echo base_url('admin/dashboard/update_match_box') ?>",
data: {tournament:data},
success: function(data) {
$('select#secondSelect').html('');
$.each(data, function(item) {
$("<option />").val(item.id)
.text(item.name)
.appendTo($('select#secondSelect'));
});
}
});