<div class="form-item"> <label class="item-label">一级分类<span class="check-tips"></span></label> <div class="controls"> <select name="yijifenlei" id="yijifenlei"> </select> </div> </div> <div class="form-item"> <label class="item-label">二级分类<span class="check-tips"></span></label> <div class="controls"> <select name="erjifenlei" id="erjifenlei"> </select> </div> </div>
js代码:
<script type="text/javascript">
var current_yijifenlei = {$info['yijifenlei']}; var current_erjifenlei = {$info['erjifenlei']}; $.post("{:U('getYijilist')}", function (result) { var res = $.parseJSON(result); $("#yijifenlei").prepend("<option value='0'>请选择</option>"); //为Select插入一个Option(第一个位 $.each(res, function (i, n) { var select = ''; if (n.id == current_yijifenlei) { select = 'selected'; } $("#yijifenlei").append("<option value='" + n.id + "' " + select + ">" + n.yijimingcheng + "</option>"); //为Select追加一个Option(下拉项) }); }); $.post("{:U('getErjilist')}", {yijiid: current_yijifenlei}, function (result) { var res = $.parseJSON(result); console.log(res) $("#erjifenlei").prepend("<option value='0'>请选择</option>"); //为Select插入一个Option(第一个位 $.each(res, function (i, n) { var select = ''; if (n.id == current_erjifenlei) { select = 'selected'; } $("#erjifenlei").append("<option value='" + n.id + "' " + select + ">" + n.erjimingcheng + "</option>"); //为Select追加一个Option(下拉项) }); }); $('#yijifenlei').change(function () { //alert($(this).children('option:selected').val()); $("#erjifenlei option").remove(); var fenlei1 = $(this).children('option:selected').val(); //这就是selected的值 $.post("{:U('getErjilist')}", {yijiid: fenlei1}, function (result) { var res = $.parseJSON(result); if(fenlei1 >0) $("#erjifenlei").prepend("<option value='0'>请选择</option>"); //为Select插入一个Option(第一个位 $.each(res, function (i, n) { $("#erjifenlei").append("<option value='" + n.id + "' >" + n.erjimingcheng + "</option>"); //为Select追加一个Option(下拉项) }); }); }); }); </script>
PHP代码:
function getYijilist() { $yijilist = M('news_yijicaidanmeiju')->select(); echo json_encode($yijilist); } function getErjilist() { $yijiid = I('yijiid', 0); if (!empty($yijiid)) { $map['yijiid'] = $yijiid; $erjilist = M('news_erjicaidanmeiju')->where($map)->select(); echo json_encode($erjilist); } else { echo '[{"id":"0","erjimingcheng":"请选择"}]'; } }