html部分
<div id="info">
省份:<select id="one"><option>请选择</option></select>
市级:<select id="two"><option>请选择</option></select>
</div>
css部分
#info{
width: 350px;
height: 30px;
font-size:12px;
float: left;
}
jquery部分
<script type="text/javascript">
$(function(){
//初始化
function init(obj){
return $(obj).html('<option>请选择</option>');
}
$.ajax({
type: 'GET',
url: './json/test.json',
dataType: 'json',
success : function(data){
getmessage(data);
}
});
function getmessage(data){
init($('#one'));
for(var i=0;i<data.x.length;i++){
var result = "<option value='" + data.x[i].id + "'>" + data.x[i].pro + "</option>";
$('#one').append(result);
}
$('#one').change(function(){
init($('#two'));
for(var j=0;j<data.y.length;j++){
if($(this).attr("value") == data.y[j].fid){
var result = "<option value='" + data.y[j].id + "'>" + data.y[j].city + "</option>";
$('#two').append(result);
}
}
});
}
});
</script>
json部分:
{
"x" : [
{
"id" : "1",
"pro" : "海南"
},
{
"id" : "2",
"pro" : "上海"
}
],
"y" : [
{
"fid" : "1",
"id" : "1-1",
"city" : "海口"
},
{
"fid" : "1",
"id" : "1-2",
"city" : "三亚"
},
{
"fid" : "2",
"id" : "2-1",
"city" : "上海"
}
]
}
成果展示
- 与上一次传入的联机下拉菜单不同之处,此处的通过ajax访问json格式的数据,或者可以通过php访问mysql,获取数据。
2. json
JSON 的四个基本规则:
1) 并列的数据之间用逗号(”,”)分隔。
2) 映射用冒号(”:”)表示。
3) 并列数据的集合(数组)用方括号(“[]”)表示。
4) 映射的集合(对象)用大括号(”{}”)表示。
注:Json里面不能加注释。
php中使用Json:
http://www.ruanyifeng.com/blog/2011/01/json_in_php.html
移动端效果下拉框效果:
http://www.grycheng.com/?p=1213