gpt4 book ai didi

jquery - 如何在 AJAX 调用上重新渲染 django 模板代码

转载 作者:行者123 更新时间:2023-12-01 00:13:36 25 4
gpt4 key购买 nike

我有一个 View ,它将分页对象(在查询集上)发送到模板,我进一步在模板中将其呈现为表格。我想做的是单击模板上分页栏上的页码,它应该进行 ajax 调用来获取该页码的分页输出并动态更新表格的内容。

查看:

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 部分尝试的大部分内容,因为我对如何使模板重新渲染返回的新帐户而不重新加载页面完全空白。

我能想到的唯一肮脏的解决方案是在 View 中生成整个 html,然后使用返回的新 html ajax 更新表 div 的 html?

使用无需重新加载页面而编写的模板渲染逻辑来重新加载表格 div 的简单方法是什么?这可以通过使表格部分成为单独的模板并包含/扩展模板来实现吗?

请注意我不能使用在模板上获取所有数据然后使用某些jquery/js libaray的分页逻辑的方法,因为完整的数据相对很大。

最佳答案

我解决了以下问题:

将表格部分分隔为模板 table.html 如下:

应用程序/table.html:

{% 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 %}

在主模板 main.html 中将此称为包含模板:

应用程序/main.html:

<div class="table-responsive">
{% include 'app/table.html' %}
</div>

现在,在我看来,我添加了一行,如果请求是 ajax 请求,则仅呈现 table.html

if request.is_ajax():
return render(request, 'app/table.html', context)
#else
return render(request, 'app/main.html', context)

重新加载分页表格:

$('.pagination_top').bootpag({
/*bootpag logic here */
}).on("page", function(event, num){
$(".table-responsive").html('').load(
"{% url 'app:accounts' %}?page=" + num
);
});

关于jquery - 如何在 AJAX 调用上重新渲染 django 模板代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39727698/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com