使用JSON代替XML做为数据传输是个不错的选择,下面我们看看django中如何使用json。
首先下载json-py的类库,http://blog.ntsky.com/wp-content/uploads/json-py-3_4.zip
我们使用关联select作为例子:
XML/HTML代码
- <select name="city_id" id="city_id" onChange="getFacilityOptions(this.value)">
- {% if city_list %}
- {% for city in city_list %}
- <option value="{{city.id}}">{{city.name}}option>
- {% endfor %}
- {% endif %}
- select>
- <select name="facility_id" id="facility_id" style="display:none">
- select>
我们选择city时候关联出facility,这里使用jquery的ajax函数
JavaScript代码
- function getFacilityOptions(city_id){
- $.ajax({
- type: "GET",
- url: "/raw/facility_list/"+city_id+"/",
- dataType: "json",
- success: function(json){
-
- $("#facility_id").show();
-
- var facilitySelect = document.getElementById("facility_id");
-
-
-
- for ( var i=facilitySelect.options.length-1; i>-1; i– ){
- facilitySelect[i] = null;
- }
-
-
- for(i=0;i
- facilitySelect.options[i] = new Option();
- facilitySelect.options[i].text = json[i].label;
- facilitySelect.options[i].value = json[i].text;
- }
- }
- })
- }
通过ajax发送请求得到json数据,然后解析json数据输出select的option
Python代码
-
- def facility_list(request,city_id):
-
- li = []
-
- city = get_object_or_404(City, pk=city_id)
- facility_list = CityFacility.objects.filter(city=city)
- for object in facility_list:
- d = {}
- d['label'] = object.facility.name
- d['text'] = object.facility.id
-
- li.append(d)
-
- return HttpResponse(json.write(li))
这里定义了list,里面包含了一组Dictionary
这样级联选择就OK了。选择city发送ajax请求django,django返回json数据,javascript解析json数据得到facility的select选择。
阅读(909) | 评论(0) | 转发(0) |