所以我正在尝试创建一个动态表单,其中第二个下拉框是根据第一个下拉列表填充的。
我正在使用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>]}
答案 0 :(得分:1)
成功回调:
$.each(json.owner_types, function(i, value){
var opt = $("<option></option>");
opt.text(value.name);
opt.val(value.id);
$("#id_plan-ownership_type").append(opt);
})
您还需要将模型数据提取为类似字典的JSON可序列化类型,这些类似于以下内容:
json["owner_types"] = [{"name": o.name, "id": o.id}
for o in OwnershipType.objects.all()] # or .filter(...)