因此,我想创建一个动态表单,其中第二个下拉框基于第一个下拉列表填充。基于关闭下拉选择创建动态下拉选项 - 卡住
我正在使用ajax
& jquery
帮助在我的django项目中构建这个动态表单,我需要一些帮助。我已经让ajax调用正常工作,并且我已将选择发回给表单,但现在我无法用我的选择填充表单。
有人能帮我把json输出变成html选项吗?
这里是我的ajax.py:
def switch_plan(request, *args, **kwargs):
from plans.models import Plan, OwnershipType, MemberType, PlanMember
from datetime import datetime
now = datetime.now()
json = {}
data = request.POST
plan_type = data.get('plan-plan_type')
print plan_type
if request.is_ajax():
if plan_type == '5':
ownership = OwnershipType.objects.all().exclude(id=3).exclude(id=8).exclude(id=9)
json['owner_types'] = ownership
return HttpResponse(simplejson.dumps(json), mimetype='application/json')
我plans.html JS代码:
<script type="text/javascript">
$(function(){
$("#id_plan-plan_type").change(function() {
q = $("form").serialize();
$.ajax({
type: "POST",
url: "{% url plans-switch_plan %}",
dataType: "json",
data: q,
success: function(json) {
//need help here
}
});
});
});
$("#id_plan-ownership_type")
是选择栏,我需要添加的选项。
编辑我的JSON输出如下{'owner_types': [<OwnershipType: Corporate/Non-Corporate>, <OwnershipType: Estate>, <OwnershipType: In Trust For>, <OwnershipType: Joint Subscriber>, <OwnershipType: Single Subscriber>, <OwnershipType: Tenants in Common>]}
另一方面:最好不要使用硬编码的'id's for'OwnershipType'或'pla视图中的n_type'对象。除了完全难以阅读外,它还取决于数据库的格式是否正确。如果你只是在某种类型的slug类型的字段上有一个索引,那么你就不会采用任何显着的速度惩罚来代替,而且它会使维护这个代码变得更容易。 – Dougal 2012-04-18 17:40:32
@Dougal谢谢,我会改变 – TheLifeOfSteve 2012-04-18 17:41:32
你试过[django-smart-selecting](https://github.com/digi604/django-smart-selects)吗? – okm 2012-04-18 17:51:39