我在尝试在web2py中创建级联下拉列表时遇到一些问题。我遵循了这个方法,然而,我(一个初学者)很难理解它背后的逻辑。
http://www.web2pyslices.com/slice/show/1526/cascading-drop-down-lists-with-ajax-2
我已经设法稍微适应它,但我在尝试向级联/序列中添加更多表时遇到了麻烦
所以目前我有下面的代码,我想要做的是从“tax_class”表中返回一个值列表,根据“tax_phylum”表中的选择结果
模型
db.define_table('tax_kingdom',
Field('name'))
db.define_table('tax_phylum',
Field('name', 'string'),
Field('kingdom_id'))
db.tax_phylum.kingdom_id.requires = IS_IN_DB(db, db.tax_kingdom.id, '%(name)s')
db.define_table('tax_class',
Field('name', 'string'),
Field('phylum_id'))
db.tax_class.phylum_id.requires = IS_IN_DB(db, db.tax_phylum.id, '%(name)s')
控制器
def index():
kingdoms = db().select(db.tax_kingdom.ALL)
if request.vars.kingdom_name:
phylum_select = db(db.tax_phylum.id == request.vars.kingdom_name).select(db.tax_phylum.ALL)
else:
phylum_select = db(db.tax_phylum.id == 1).select(db.tax_phylum.ALL)
return dict(kingdoms=kingdoms, phylum_select=phylum_select)
def phylum():
phylums = db(db.tax_phylum.kingdom_id == request.vars.kingdom_name).select(db.tax_phylum.ALL)
result = ""
for p in phylums:
result += "<option value='" + str(p.id) + "'>" + p.name + "</option>"
return XML(result)
视图
{{extend 'layout.html'}}
<form enctype="multipart/form-data" action="{{URL()}}" method="post">
<select name='kingdom_name'
onchange="jQuery('#kingdom_name').empty();
ajax('phylum', ['kingdom_name'], 'phylum_name');">
{{for kingdom in kingdoms:}}
<option value="{{=kingdom.id}}"
{{=" selected='selected'" if str(kingdom.id)==request.vars.kingdom_name else ""}}>
{{=kingdom.name}}
</option>
{{pass}}
</select>
<select id='phylum_name' name='phylum_name' >
<!-- loop through the index function i -->
{{for phylum in phylum_select:}}
<option value="{{=phylum.id}}"
{{=XML(" selected='selected'") if str(phylum.id)==request.vars.phylum_name else ""}}>
{{=phylum.name}}</option>
{{pass}}
</select>
</form>