使用JSON代替XML做为数据传输是个不错的选择,下面我们看看django中如何使用json。
首先下载json-py的类库,http://blog.ntsky.com/wp-content/uploads/json-py-3_4.zip
我们使用关联select作为例子:
<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函数
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;
}
// 创建select选项
for(i=0;i<json.length;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
# 城市设施列表
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选择。