问题
So I am trying to create a dynamic form where the 2nd dropdown box is populated based on the first dropdown.
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.
Can someone help me make the json output turn into html options?
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')
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") is the select field that I need to add the options to.
Edit My json output is as follows {'owner_types': [<OwnershipType: Corporate/Non-Corporate>, <OwnershipType: Estate>, <OwnershipType: In Trust For>, <OwnershipType: Joint Subscriber>, <OwnershipType: Single Subscriber>, <OwnershipType: Tenants in Common>]}
回答1:
In your success callback:
$.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);
})
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(...)
来源:https://stackoverflow.com/questions/10214618/creating-dynamic-dropdown-options-based-off-dropdown-selection-stuck