Home » Code » 简单的省市区三级联动

简单的省市区三级联动

这里,数据源在后端数据库,每次切换都要请求后端获得数据。关键点在于一个select切换后,往后的所有select都要更新,而且更新是需要按顺序从左到右的更新。

本实例借助jQuery的延迟对象Deferred实现:

var province = '广东省', city = "深圳市", district = "罗湖区";
var provinceSelect = $("select[name=province]"), citySelect = $("select[name=city]"), districtSelect = $("select[name=district]");
var provinceUri = "{{ route('cnarea.province') }}", cityUri = "{{ route('cnarea.city') }}", districtUri = "{{ route('cnarea.district') }}"; 

function setSelect(select, dataSourceUri, firstOptionText, selectedName) {
    var def = $.Deferred();
    $.get(dataSourceUri, function(response) {
        var options = ['<option value="">' + firstOptionText + '</option>'];
        if (response.ret == 0) {
            var pid, selected;
            $.each(response.data, function(index, item) {
                if (item.name == selectedName) {
                    pid = item.id;
                    selected = " selected";     
                } else {
                    selected = "";  
                }
                options.push('<option value="' + item.id + '"' + selected + '>' + item.name + '</option>');
            });
        }
        select.html(options.join(""));
        def.resolve();
    }, "json");
    return def.promise();
}

function setProvince(province) {
    return setSelect(provinceSelect, provinceUri, '--省--', province);
}
function setCity(city) {
    return setSelect(citySelect, cityUri + "?pid=" + provinceSelect.val(), '--市--', city);
}
function setDistrict(district) {
    return setSelect(districtSelect, districtUri + "?pid=" + citySelect.val(), '--区--', district);
}

function provinceChange() {
    setCity().then(function() {
        setDistrict();
    })
}

function cityChange() {
    setDistrict();
}

provinceSelect.on("change", provinceChange);
citySelect.on("change", cityChange);

//初始化
setProvince(province).then(function(){
    console.log("set province done!");
    return setCity(city);
}).then(function() {
    console.log("set city done!");
    return setDistrict(district);
}).done(function() {
    console.log("set district done!");
    console.log("all done!");
});

每请求并渲染完一个select,再依据前一个的选择继续请求数据数据渲染下一个select!一个简单的省市区三级联动就完成了。近期文章产量较少,水一篇充数,😂。

PS:后端数据来自这里

Leave a Reply

Your email address will not be published. Required fields are marked *

*

Time limit is exhausted. Please reload CAPTCHA.