2016-12-17 20 views
1

我想根據ajax調用的響應更新我的模板中的列表。據我所知,不可能直接從視圖中發回一個列表並迭代它。這就是爲什麼我試圖想出一個替代方案,但我有點卡住了。這裏是我當前的代碼:通過ajax更新可變長度html列表

  • 模板(縮短):

    {% for a in attributes %} 
        <li> a.name </li> 
    {% endfor %} 
    
  • 阿賈克斯:

    $.ajax({ 
        url: "{% url 'main:next_attributes' %}", 
        data: {'next':'abc'}, 
        datatype : 'json', 
        success: function (data) { 
        console.log("Success");}}) 
    

的console.log應該由什麼來取代它在新值迭代並更新上面列表中的值。這裏棘手的部分是,列表項目的數量可能會不同於以前(更低或更高)。然而,我不清楚這個視圖的反應是怎樣的,這就是爲什麼它仍然有一個佔位符(見下一部分)。

  • Views.py:

    def next_attributes(request): 
        keyword = request.GET.get('next', None) 
        next_attributes = Attributes.objects.filter(keyword=keyword)  
        data = {'attributes':next_attributes} 
        return JsonResponse(data) 
    

這裏的問題,我無法通過JsonResponse返回查詢結果..

總結: 我希望得到一個新的查詢結果基於ajax請求中給出的過濾器,並更新我的模板中的列表(可變長度,基於查詢結果)。我會很感激任何指針。

+0

你可以用'Attributes.objects.filter(關鍵字=關鍵字).values假設你<li>(' 名')',但要記住,你的模板代碼運行在服務器上,而不是在瀏覽器中,所以你必須使用JavaScript來插入數據.. – thebjorn

回答

1

正如@thebjorn指出的那樣,您可以使用Attributes.objects.filter(keyword=keyword).values('name')來獲取值列表。一個完整的例子是以下幾點:

def next_attributes(request): 
    keyword = request.GET.get('next', None) 
    next_attributes = Attributes.objects.filter(keyword=keyword).values('name') 
    data = {'attributes':next_attributes} 
    return JsonResponse(data) 

我不能完全確定是否.values返回的JSON序列化對象,但本質將是。

然後,預期目標應該是這樣的:

{'attributes': [{'name': 'name1'}, {'name': 'name2'}]} 

然後,因爲你使用jQuery,你可以做到以下幾點。 'ID爲myList s的包裹在一個<ul>

$.ajax({ 
    url: "{% url 'main:next_attributes' %}", 
    data: {'next':'abc'}, 
    datatype : 'json', 
    success: function (data) { 
     $('#myList').empty(); // Clear old values 
     data.attributes.forEach(function(element){ 
      $('#myList').append("<li>"+element.name+"</li>"); // Please note that this does not include any sanitization of the data. Be careful with that 
     } 
    } 
}