摘要:JQuery + PHP:主選單變更後,變更子選單
HTML
<select id="main_select" name="main_select"> .... </select>
<select id="sub_select" name="sub_select"></select>
JavaScript
<script>
$(document).ready(function(){
var get_sub_list = function(){
var sub_id= '<?php echo $sub_id; ?>';
var defaultOptionText = '----請選擇----';
var primaryId = $('#main_select').val();
var params = {
primary_id: primaryId
};
$.ajax({
url: 'your_url',
dataType: 'json',
async: false,
data: params,
success: function(data){
if (data.error_code == 200) {
var list = $('#sub_select').empty();
$('<option>').val('')
.text(defaultOptionText)
.appendTo(list);
$.each(data.raw, function(index, item) {
$('<option>').val(item.value)
.attr('selected', ((item.value == sub_id)))
.text(item.text)
.appendTo(list);
});
}
}
});
}
$('#main_select').change(function(){
get_sub_list();
});
get_sub_list();
});
</script>
PHP
//get $primary_id to select database -- 自己取得primary_id 做對應的資料取得
$items = array();
$i=0;
while($i<3)
{
unset($d);
$d['value'] = $i;
$d['text'] = "ITEM".$i;
array_push($items, $d);
}
$ret['error_code'] = 200;
$ret['error_msg'] = '';
$ret['raw'] = $items;
echo json_encode($ret);