【发布时间】:2012-04-30 04:09:20
【问题描述】:
所以我正在尝试创建一个动态表单,其中第二个下拉框根据第一个下拉列表填充。
我正在使用 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>]}
【问题讨论】:
-
顺便说一句:对于视图中的
OwnershipType或plan_type对象,最好不要使用硬编码的ids。除了完全难以阅读之外,它还取决于数据库的格式是否正确。如果你只是在某种 slug 类型的字段上有一个索引,那么使用它不会对速度造成任何明显的损失,而且它会使维护这段代码变得更加容易。 -
@Dougal 谢谢,我会改的
-
你试过django-smart-selects吗?
标签: jquery ajax django django-templates