0
我有一堆代碼,我認爲應該從另一個「主題」選擇框中的值中填充「類別」選擇框。使用Ajax和jQuery從Django中的查詢集填充選擇框
views.py
def get_categories(request, subject_id):
subject = Subject.objects.get(pk=subject_id)
categories = subject.category_set.all()
category_dict = {}
for cat in categories:
category_dict[cat.id] = cat.name
return HttpResponse(json.dumps(category_dict), content_type="application/json")
urls.py
url(r'^get_categories/(?P<subject_id>\d+)/$', views.get_categories, name='get_categories'),
jQuery的
$(document).ready(function(){
$('select[name=subject]').change(function(){
subject_id = $(this).val();
request_url = '/get_categories/' + subject_id + '/';
$.ajax({
url: request_url,
success: function(data){
$.each(data[0], function(key, value){
$('select[name=category]').append('<option value="' + this.key + '">' + this.value +'</option>');
});
}
})
})
});
請求傳遞JSON數據,據我所知, JavaScript是給錯誤:
Uncaught TypeError: Cannot read property 'length' of undefined
我厭倦了將數據[0]更改爲數據並刪除了錯誤,但所有字段都顯示爲在選擇框中未定義。
還要注意,它是真正低效的查詢每次選擇。在每個循環之前執行一次,將其存儲在局部變量中,並從循環內部引用它。 –