django+jquery 实现级联选择菜单
最近在做一个基于django框架的项目,需要实现级联选择菜单,比如省-市-区,记录下来,希望能帮助碰到同样问题的人。
--------------------------------------------------------------------------------------------
无代码无真相,直接上代码:
js代码:
<script src="/site_media/js/jquery-1.5.2.min.js" type="text/javascript"></script> <script type="text/javascript"> function getCityOptions(province_id){ $.ajax({ type: "GET", url: "/getCityList?provinceID="+province_id, dataType:'json', success: function(data,textStatus){ var citySelect = document.getElementById("id_city"); for ( var i=citySelect.options.length-1; i>-1; i--){ citySelect[i] = null; } if(data.length > 0) { $("#id_city").show(); for(i=0;i<data.length;i++){ citySelect.options[i] = new Option(); citySelect.options[i].text = data[i].label; citySelect.options[i].value = data[i].text; } }else $("#id_city").hide(); } }) } </script>
模板代码:
<label>省市:</label> {{form.province}} {{form.city}}
Form.py:
provinces = Province.objects.all() PROVINCE_CHOICES = [] for province in provinces: PROVINCE_CHOICES.append([province.id, province.provinceName]) class myForm(forms.Form): province = forms.ChoiceField(widget = forms.Select(attrs={'class':'select', 'onChange':'getCityOptions(this.value)'}), choices = PROVINCE_CHOICES, label= u'选择省') city = forms.ChoiceField(widget = forms.Select(attrs={'class':'select', 'onChange':'getDistrictOptions(this.value)','style':'display:none'}), label = u'选择市')
model.py:
class Province(models.Model): provinceName = models.CharField(max_length = 20) class City(models.Model): cityName = models.CharField(max_length = 20) provinceID = models.ForeignKey(Province)
view.py
def city_list(request): city_list = [] province = request.GET['provinceID'] citys = City.objects.filter(provinceID = province) for city in citys: c = {} c['label'] = city.cityName c['text'] = city.id city_list.append(c) return HttpResponse(simplejson.dumps(city_list), mimetype='application/json')