根据下拉式选择创建动态下拉选项 - 卡住了 [英] Creating dynamic dropdown options based off dropdown selection - stuck
问题描述
所以我试图创建一个动态表单,第二个下拉框是根据第一个下拉菜单填充的。
So I am trying to create a dynamic form where the 2nd dropdown box is populated based on the first dropdown.
我正在使用 ajax
& jquery
帮助我在django项目中构建这个动态表单,我需要一些帮助。我已经得到ajax电话正常工作,我已经把我的选择发回了表格,但现在我无法填写表单,我的选择。
I am using ajax
& jquery
to help build this dynamic form in my django project, and I need a bit of help. I have got the ajax call to work properly, and I have sent my choices back to the form, but now I am having trouble populating the form with my choices.
可以有人帮我把json输出变成html选项?
Can someone help me make the json output turn into html options?
这是我的ajax.py:
Here is my 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代码:
My plans.html js code:
<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)
是我需要添加选项的选择字段。
$("#id_plan-ownership_type")
is the select field that I need to add the options to.
编辑我的json输出如下 {'owner_types':[< OwnershipType:Corporate / Non-Corporate>< OwnershipType:Estate>< OwnershipType:In Trust For>,< OwnershipType :Joint Subscriber>< OwnershipType:Single Subscriber>< OwnershipType:Tenants in Common>]}
推荐答案
在您的成功回调中:
$.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序列化类型,如字典,这些类型如下:
You also need to extract your model data into a JSON-serializable type like a dictionary, something along the lines of:
json["owner_types"] = [{"name": o.name, "id": o.id}
for o in OwnershipType.objects.all()] # or .filter(...)
这篇关于根据下拉式选择创建动态下拉选项 - 卡住了的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!