我有一個視圖,它將查詢集中的分頁對象(發送到查詢集)發送到模板,我將模板作爲表格進一步呈現。我想要做的是點擊模板上的分頁欄上的頁碼,它應該進行ajax調用,以獲得該頁碼的分頁輸出,並動態更新表的內容。如何在AJAX調用中重新呈現Django模板代碼
查看:
def accounts(request):
#Including only necessary part
accounts_list = Accounts.objects.all()
paginator = Paginator(accounts_list, 25)
page = request.GET.get('page')
try:
accounts = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
accounts = paginator.page(1)
except EmptyPage:
# If page is out of range, deliver last page of results.
accounts = paginator.page(paginator.num_pages)
context['accounts'] = accounts
return render(request, template, context)
模板加載此爲:
{% if accounts %}
<table id="acc">
<tr>
<th>Field 1</th>
...
<th>Field N</th>
</tr>
{% for item in accounts %}
<tr>
<td>{{ item.field1 }}</td>
...<!-- Some complex logic with template tags too in here -->
<td>{{ item.fieldN }}</td>
</tr>
{% endfor %}
</table>
{% endif %}
現在對於分頁欄,我使用Bootpag's library,我可以渲染的東西爲:
$('.pagination_top').bootpag({
/*bootpag logic here */
}).on("page", function(event, num){
//$.ajax loading here where I can update the table div with new output
//or make the table div "template code" reload without reloading page
}
對不起,我有沒有顯示我在ajax部分嘗試過的東西,因爲我完全空白瞭如何讓模板重新呈現無需重新加載頁面而返回的新帳戶。
我能想到的唯一骯髒的解決方案是在視圖中生成我的整個html,然後用新的html ajax返回更新表格div的html?
什麼是簡單的方法來說,重新加載表格div使用模板渲染邏輯寫入沒有重新加載頁面?這可以通過將表格部分作爲單獨的模板幷包含/擴展模板來實現?
請注意,我不能使用一種方法獲取模板上的所有數據,然後使用一些jquery/js libaray的分頁邏輯,因爲完整的數據是相當大的。
你的js腳本仍在重新加載頁面,頁面url是否隨着每次點擊而改變? – sgauri