我需要使用set_select,但select2的选项是从带有ajax的控制器调用的。我该怎么办?
我的控制器:
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);
}
}
我的模特:
public function getCategorylocal($location_id)
{
$query = $this->db->get_where('categories', array('location_id' => $location_id));
return $query->result();
}
我的观点:
<select name="parent_id" id="category" class="form-control">
<option value=""><?php echo lang('text_none'); ?></option>
</select>
和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');});
是否可以使用控制器中的set_select?...我在视图中使用set_select但在控制器中没有...
答案 0 :(得分:0)
我没有看到您在视图中使用set_select的位置,但由于您返回的是选项的HTML片段,因此您可以在不执行json编码的情况下返回视图。
$this->load->view('view_that_builds_options', $this->locationscats);
或构建$ 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;
}