[英]How can I use set_select with Ajax in Codeigniter
I need use set_select but the options of the select2 are called from controller with ajax. 我需要使用set_select,但是select2的选项是使用ajax从控制器调用的。 How can I do?
我能怎么做?
My controller: 我的控制器:
public function getCategoryByLocation()
{
$location_id = $this->input->post('location_id');
$locationscats = $this->Categories_model->getCategorylocal($location_id);
if(count($locationscats) > 0)
{
$select = '';
$select .= '<option value="">'.$this->lang->line('text_none').'</option>';
foreach ($locationscats as $locationscat) {
$select .='<option value="'.$locationscat->category_id.'">'.$locationscat->name.'</option>';
}
echo json_encode($select);
}else{
$select = '';
$select .= '<option value="">'.$this->lang->line('text_none').'</option>';
echo json_encode($select);
}
}
My Model: 我的模特:
public function getCategorylocal($location_id)
{
$query = $this->db->get_where('categories', array('location_id' => $location_id));
return $query->result();
}
My View: 我的观点:
<select name="parent_id" id="category" class="form-control">
<option value=""><?php echo lang('text_none'); ?></option>
</select>
And the Ajax call.. 还有Ajax电话
$(document).ready(function() {
$('#input-location').on('change', function() {
var location_id = this.value;
$.ajax({
url:"<?php echo site_url("/categories/getCategoryByLocation"); ?>",
type: "POST",
data: {'location_id' : location_id},
dataType: 'json',
success: function(data){
$('#category').html(data);
},
error: function(){
alert('Error occur...!!');
}
});
});
$("#input-location").trigger('change');});
Is possible used set_select from the controller?... I'm using set_select in the views but no in controller... 可以从控制器中使用set_select吗?...我在视图中使用set_select,但在控制器中没有...
I don't see where you using set_select in your view but since you're returning an HTML fragment of options, you can just return the view without doing json encoding. 我看不到在视图中使用set_select的位置,但是由于您要返回选项的HTML片段,因此无需执行json编码就可以返回视图。
$this->load->view('view_that_builds_options', $this->locationscats);
Or build the $select var and echo that... 或构建$ select var并回显...
public function getCategoryByLocation() {
$this->load->helper('form');
$location_id = $this->input->post('location_id');
$locationscats = $this->Categories_model->getCategorylocal($location_id);
$select .= '<option value="">'.$this->lang->line('text_none').'</option>';
if(count($locationscats) > 0) {
foreach ($locationscats as $locationscat) {
$select .='<option value="'.$locationscat->category_id.'">'
// assume your select is named 'category' by the id='category'.
$select .= set_select('category', $NoIdeaWhatValueYouAreCheckingForGoesHere);
$select .= $locationscat->name.'</option>';
}
}
echo $select;
} }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.