Codeigniter 上的动态相关下拉列表国家和州
Posted
技术标签:
【中文标题】Codeigniter 上的动态相关下拉列表国家和州【英文标题】:Dynamic Dependent Dropdown List Country and State on Code Igniter 【发布时间】:2019-05-25 23:38:02 【问题描述】:我正在开发在 CodeIgniter 上使用动态或依赖下拉列表的项目。这是我的菜鸟逻辑,视图中的国家值传递给模型,然后模型从视图中获取具有相同国家值的状态数据,然后控制器从模型中获取状态数据并将其再次传递给视图。问题是状态下拉列表什么也没显示。 对不起,我是编码新手。
//This is the Controllers (Pkl.php)
$data['all_country'] = $this->Server_Model->get_country_model();
$data['all_state'] = $this->Server_Model->get_state_model();
$this->load->view('contents/page_dashboard', $data);
//This is the Models (Server_Model.php)
function get_country_model()
$db_jarlap = $this->load->database('gis_bali', TRUE);
$db_jarlap->select("*");
$db_jarlap->from("country");
$que = $db_jarlap->get();
return $que->result();
function get_state_model()
$kakakoko = filter_input(INPUT_POST, 'country_id');
$db_jarlap = $this->load->database('gis_bali', TRUE);
$db_jarlap->select("*");
$db_jarlap->from("state");
$db_jarlap->where(" id_country = $kakakoko ");
$que = $db_jarlap->get();
return $que->result();
//This is the Views Content (page_dashboard.php)
<script src="<?php echo base_url() ?>resources/js/jquery-3.3.1.min.js"</script>
<script>
$(document).ready(function()
$('#formCountry').change(function()
var country_id = $(this).val();
$.ajax(
url: "<?php echo base_url() ? >application/models/Server_Model.php",
method: "POST",
data: country_id:country_id,
success: function(data)
$('#formState').html(data);
);
);
);
</script>
<select name="formCountry" id="formCountry">
<?php foreach($all_country as $semua_country): ?>
<option value="<?php echo $semua_country->id_country; ?>"><?php echo $semua_country->nama_country; ?></option>
<?php endforeach; ?>
</select>
<select name="formState" id="formState" >
<?php foreach($all_state as $semua_state): ?>
<option value="<?php echo $semua_state->id_state; ?>"><?php echo $semua_state->nama_state; ?></option>
<?php endforeach; ?>
</select>
感谢您的帮助。
【问题讨论】:
【参考方案1】:你不应该直接调用模型,而是调用Pkl
控制器,我假设你在Pkl
控制器上使用index()
方法:
$(document).ready(function ()
$('#formCountry').change(function ()
var country_id = $(this).val();
$.ajax(
url: "<?php echo base_url() ?>pkl", // using Pkl controller
method: "POST",
data:
country_id: country_id
,
success: function (data)
$('#formState').html(''); // empty the select option element
$.each(data, function() // format each option returned from Pkl controller
$("#formState").append('<option value="'+ this.id_state +'">'+ this.nama_state +'</option>');
);
);
);
);
【讨论】:
以上是关于Codeigniter 上的动态相关下拉列表国家和州的主要内容,如果未能解决你的问题,请参考以下文章