我的数据库中有两个表:
1.动物种类2. Breeds
动物类型:
type_id | name
------------------------
1 | Dog
2 | Cat
3 | etc...
breed
ID | type_id | name
---------------------------
1 | 1 | Labrador
2 | 1 | Putbull
3 | 2 | Persian
etc.....
在我的首页上,我想显示选择下拉菜单,其中包含根据动物类型选择的动物类型和品种。
1. 选择动物类型
<select id="animal_type">
<option value="<?php $type->id">Dog</option>
<option value="<?php $type->id">Cat</option>
</select>
2. 如果用户选择类型,则取消禁用根据类型选择品种列表
<!-- user select Dog type! fetch all dog breeds -->
<select id="breeds" disabled>
<option value="<?php $type->id">Labrador</option>
<option value="<?php $type->id">Pitbull</option>
</select>
所以我想根据所选的女巫类型从我的控制器加载所有品种。我尝试用ajax来解决这个问题,但我对他不太好。
我尝试这个,但不知道如何附加新选项来选择下拉列表。
Script :
$(document).ready(function() {
// $("#breeds").attr('disabled', true);
// check if selected
if($("#animal_type").find('option:selected').val() == 0) {
$("#breeds").attr('disabled', true);
}
$('#animal_type').change(function(){
// get value of selected animal type
var selected_animal_type = $(this).find('option:selected').val();
$.ajax({
url : "url-to-site/index.php/account/getBreedsByTypeID/1",
type:'POST',
dataType: 'json',
success: function(response) {
$("#breeds").attr('disabled', false);
//alert(response); // show [object, Object]
var $select = $('#breeds');
$select.find('option').remove();
$.each(response,function(key, value)
{
$select.append('<option value=' + key + '>' + value + '</option>'); // return empty
});
}
});
});
});
JSON 返回我的自定义品种名称
[{"breed_name":"Nema\u010dki prepeli\u010dar"},{"breed_name":"Irski vodeni \u0161panijel"},{"breed_name":"Barbe (Barbet)"},{"breed_name":"Lagoto
My controller `mysite.com/index.php/account/getBreedsByTypeID/1`
此 url 返回以下编码的 JSON
$breeds = $this->animal_breed->findAllBreedsByType($id); // Model @return array
return json_encode($breeds);
那么如何根据类型将该结果附加到我的选择中呢?
您能提供一个例子来解决这个问题吗?谢谢。