2015-07-19 58 views
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]更改爲數據並刪除了錯誤,但所有字段都顯示爲在選擇框中未定義。

回答

1

如果你的JSON是有效的,你應該使用data(不data[0]),你的問題是最有可能在這裏:

$('select[name=category]').append('<option value="' + this.key + '">' + this.value +'</option>'); 

在$ this關鍵字。每次返回值,但作爲一個對象。請參閱: http://api.jquery.com/jquery.each/

The value can also be accessed through the this keyword, but Javascript will always wrap the this value as an Object even if it is a simple string or number value.

所以this.keythis.value會給你undefined

這應該工作(同樣,假設你的JSON是有效的):

success: function(data){ 
    $.each(data, function(key, value){ 
     $('select[name=category]').append('<option value="' + key + '">' + value +'</option>'); 
    }); 
} 
+1

還要注意,它是真正低效的查詢每次選擇。在每個循環之前執行一次,將其存儲在局部變量中,並從循環內部引用它。 –

相關問題