2013-02-09 66 views
3

我被這個問題困住了:我有一個搜索結果頁面,其中有幾個結果。我希望用戶能夠根據一些標準對結果進行排序。我在AJAX中這樣做。問題是如何將來自服務器的已排序數據再次呈現給字段。排序搜索結果的查詢集並通過ajax回顯

function sort(){ 
    var sortid = $('#sort').val(); 
    $.ajax({ 
     type: "POST", 
     url: "/sort/", 
     data: { sortid: sortid }, 
    }).done(function(data){ 
     // how to render this sorted 'data' back to <td>s? 
    }); 
} 

這是我的綁定代碼:

<select onchange="sort()" id="sort"> 
    <option>price</option> 
    <option>rate</option> 
</select> 

這就是結果的地方:

<tr class="result"> 
    <td> 
     <li>{{loc.locationname}}</li> 
    </td> 
    <td>  
     <li>{{loc.rating}}</li> 
    </td> 
    <td> 
     <li>{{loc.price}}</li> 
    </td> 
</tr> 
+0

什麼是你的Ajax調用的結果? – Chris 2013-02-09 11:47:02

+0

@Chris,來自服務器的排序後的queryset。我只想知道如何回到'td'' – doniyor 2013-02-09 11:48:46

+0

@RoryMcCrossan的方式,很容易在我的代碼中看到這一點:'''' – doniyor 2013-02-09 11:52:01

回答

2

您的視圖可以返回渲染片斷喜歡,你可以只呈現到客戶端上的一個div

你的Ajax調用可以像這樣

function sort(){ 
    var sortid = $('#sort').val(); 
    $.ajax({ 
     type: "POST", 
     url: "/sort/", 
     data: { sortid: sortid }, 
    }).done(function(data){ 
     $('#results-div').html(data.html); 
    }); 
} 

一個例子視圖

import json 
from django.shortcuts import HttpResponse 
from django.template import loader, RequestContext 


def my_view(request, query=None): 
    # trivialized example 

    sortid = request.REQUEST.get('sortid') 

    # you might want to store the results into cache 
    results = MyModel.objects.filter(name__icontains=query).order_by(sortid) 

    if request.is_ajax(): 
     t = loader.get_template('search_results.html') 
     html = t.render(RequestContext({'results': results)) 
     return HttpResponse(json.dumps({'html': html})) 
    # handle the other cases here 

search_results.html裏面,你會只呈現結果到表

{% for loc in results %} 
<tr class="result"> 
    <td> 
     <li>{{loc.locationname}}</li> 
    </td> 
    <td>  
     <li>{{loc.rating}}</li> 
    </td> 
    <td> 
     <li>{{loc.price}}</li> 
    </td> 
</tr> 
{% endfor %} 
+0

謝謝,這應該工作。但這與「render_to_response」沒有區別, – doniyor 2013-02-10 14:26:30

1
function(data){ 
    var tablehtml='<tbody>' 
    $.each(data,function(i,res) { 
     tablehtml+='<tr class="result">'+ 
        '<td><li>'+res.locationname+'</li></td>'+ 
        //... 
     }); 
    $("table").html(tablehtml+'</tbody'>) 
    } 

注意:我已經添加,因爲添加的HTML這樣的tbody標籤如果html被封裝在單個父節點中比如果它是(長)節點列表要快得多

EUH ...編輯而是利用這一點,你需要在你所期待的JSON響應(datatype:'json')的阿賈克斯告訴這是不是這樣的,現在

還你需要發送一個特定的頭(「內容類型:應用程序/ JSON」)從

,如果你堅持要送,然後HTML解析服務器端數據的服務器(把它包),並在回調立即將其追加

如果你想

重新考慮你的排序功能概念,如果數據不是那麼大&如果你可以gzip;我會立即加載所有數據&在js中進行排序(沒有更多的服務器調用功能將爲用戶提供更快的方式:稍微等待頁面加載但瞬間排序然後

+0

我認爲他雖然得到了HTML,而不是JSON。 – 2013-02-09 12:01:19

+0

耶看到它現在,我的壞,但在這種情況下,JSON似乎更合適 – mikakun 2013-02-09 12:03:13

+0

我同意。這將使排序更直接。所有你需要做的就是修改DOM,一旦排序就從JSON添加數據。 – 2013-02-09 12:03:58