0
我寫這個函數的方式現在可以工作了,我只是想知道是否有更好或更有效的方式來編寫它。這是一個ajax調用,可以獲得進一步過濾地理位置的列表,例如,如果選擇縣,那麼它將獲得該州所有縣的列表。 我仍然在學習編碼,並希望在使用良好的編碼實踐方面做得更好。更有效的書寫這個功能的方法? (Django,AJAX)
$.ajax({
url : "filters",
type : "POST",
data : { search : selected_state, geog : selected_geog },
success: function(data) {
$.each(data, function(i, v) {
switch(selected_geog) {
case 'County':
case 'Dma':
filters.push(v.fields.name);
break;
case 'Zip':
var exists = $.inArray(v.fields.zcta, data_check);
if (exists < 0) {
data_check.push(v.fields.zcta);
}
data_check.sort();
var exists2 = $.inArray(v.fields.county, filters);
if (exists2 < 0) {
filters.push(v.fields.county);
}
filters.sort();
break;
case 'CD':
filters.push(v.fields.cd114fp);
break;
case 'Zones':
var exists = $.inArray(v.fields.p_dma, filters);
if (exists < 0) {
filters.push(v.fields.p_dma);
}
filters.sort();
var exists2 = $.inArray(v.fields.owner, attrfilters);
if (exists2 < 0) {
attrfilters.push(v.fields.owner);
}
SHPconverter.attrfilters.sort();
var exists3 = $.inArray(v.fields.scode, data_check);
if (exists3 < 0) {
data_check.push(v.fields.scode);
}
data_check.sort();
break;
}
})
}
})
,這裏是Django的視圖
def filters(request):
searchVar = request.POST.getlist('search[]')
geogVar = request.POST.get('geog')
if geogVar == 'County':
county_as_json = serialize(
'json', County.objects.filter(
state__in=searchVar).order_by('state', 'name'))
return HttpResponse(county_as_json, content_type='json')
elif geogVar == 'DMA':
dma_as_json = serialize(
'json', Dma.objects.filter(
state__in=searchVar).order_by('state', 'name'))
return HttpResponse(dma_as_json, content_type='json')
elif geogVar == 'CD':
cd_as_json = serialize(
'json', Cd.objects.filter(
state__in=searchVar).order_by('state', 'cd'))
return HttpResponse(cd_as_json, content_type='json')
elif geogVar == 'Zip':
zip_as_json = serialize(
'json', Zip.objects.filter(
state__in=searchVar).order_by('state', 'county'))
return HttpResponse(zip_as_json, content_type='json')
elif geogVar == 'Zones':
zones_as_json = serialize(
'json', Zones.objects.filter(
state__in=searchVar).order_by('sname'))
return HttpResponse(softzones_as_json, content_type='json')
嘗試http://codereview.stackexchange.com/ –