附加< options>以< select>使用AJAX&的PHP [英] Append <options> to <select> using AJAX & PHP
问题描述
我的数据库中有两个表:
I have two tables in my database:
1..动物类型 2.品种
animal_type:
type_id | name
------------------------
1 | Dog
2 | Cat
3 | etc...
品种
ID | type_id | name
---------------------------
1 | 1 | Labrador
2 | 1 | Putbull
3 | 2 | Persian
etc.....
在我的首页上,我想显示带有动物类型的选择下拉菜单,并根据动物类型选择品种.
On my front page I want to show select dropdown menu with animal types and breeds select based on animal type.
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来解决这个问题,但对他来说并不是很好.我尝试这样做,不知道如何添加新选项来选择下拉菜单.
So I want to load all breeds from my controller based on witch type is selected. I try to slove this with ajax but am not realy good with him. I try this and dont know how to append new option to select dropdown.
脚本:
$(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`
此网址返回以下编码的JSON
This url returns the following encoded JSON
$breeds = $this->animal_breed->findAllBreedsByType($id); // Model @return array
return json_encode($breeds);
那么如何根据类型将结果附加到我的选择中呢?
So how can I append that result to my select based on type?
您能提供一个解决此问题的示例吗?谢谢.
Could you offer an example to solve this problem? Thanks.
推荐答案
$.ajax({
url : "url-to-site/index.php/account/getBreedsByTypeID/1",
type:'POST',
dataType: 'json',
success: function(response) {
$("#breeds").attr('disabled', false);
$.each(response,function(key, value)
{
$("#breeds").append('<option value=' + key + '>' + value + '</option>');
});
}
});
这篇关于附加< options>以< select>使用AJAX&的PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!