【发布时间】:2016-01-23 18:29:06
【问题描述】:
我正在尝试从另一个下拉列表的值中填充一个下拉列表,所以这是我的 ajax 代码。
$(document).ready(function() {
$('#category').change(function () {
var category = $('#category :selected').val(); // <-- change this line
console.log(category);
$.ajax({
type: "POST",
url: "<?php echo base_url('Ajax_test_controller/populateSubcategory'); ?>",
data: category,
dataType: 'json',
success: function(data) {
console.log(data);
$(data).each(function(){
$("#subcategory").append($('<option>', {
value: this.id,
text: this.subcategory,
}));
})
},
error: function(errorw) {
alert("hi");
}
});
});
});
这是我的控制器
public function populateSubcategory(){
$category_id = $this->input->post('category');
$data = $this->ajax_test_model->getSubCategory($category_id);
echo json_encode($data);
}
这是我的模特
function getSubCategory($category_id){
$this->db->select('id, subcategory');
$this->db->from('subcategory');
$this->db->where('category_id', $category_id);
$this->db->order_by("subcategory", "asc");
$query = $this->db->get();
return $query->result();
}
这是我的看法
<div>
<div class="form-group">
<label class="control-label">Category : </label>
<select name="category" id="category">
<option value="0">Select Category</option>
<?php
if(is_array($category) || is_object($category)){
foreach($category as $category_row){
echo '<option value="'. $category_row->id .'">'. $category_row->category .'</option>';
}
}
?>
</select>
<label class="control-label">Subcategory : </label>
<select name="subcategory" id="subcategory">
</select>
</div>
</div>
我不知道我的语法是否有错误,但每当我尝试将模型更改为
function getSubCategory($category_id){
$cat = 1;
$this->db->select('id, subcategory');
$this->db->from('subcategory');
$this->db->where('category_id', $cat);
$this->db->order_by("subcategory", "asc");
$query = $this->db->get();
return $query->result();
}
我用这个模型得到了我想要的结果。但这只是为了检查我是否从查询中得到任何信息。
我的猜测是 category_id 没有传递给我的模型。但是当我检查category_id的值时,它等于1。
而且我没有发现任何问题。感谢您提供有关如何解决此问题的意见。谢谢。
【问题讨论】:
标签: php ajax codeigniter