gpt4 book ai didi

jquery - Django 数据表加载 ajax 数据加载

转载 作者:行者123 更新时间:2023-11-28 16:36:05 24 4
gpt4 key购买 nike

可能我还不明白 urls.py 是如何工作的...但我不知道如何使用数据表的“bServerSide”加载数据...我认为我的 urls.py 有问题.我使用 Django、datatables.js,这是我的代码:

main.html

<table cellpadding="0" cellspacing="0" border="0" id="example1">
<thead>
<tr><th>Name</th></tr>
</thead>
<tbody></tbody>
</table>

<script type="text/javascript" language="javascript" class="init">
$(document).ready(function() {
$('#example1').dataTable( {
"bServerSide": true,
"sAjaxSource": "main.html/getdata_json",
"bProcessing": true,
} );
} );
</script>

View .py

def myajaxview(request):
report = []
start = request.GET['iDisplayStart']
length = request.GET['iDisplayLength']
query = name.objects.all() #or any kind of queryset
query = query[start:start+length]
for q in query:
report.append(json.dumps(q.nome_struttura))
json = json.dumps(report)
return HttpResponse(json, content_type='application/json')

网址.py

  urlpatterns = i18n_patterns('',
...
url(r'^getdata_json$', 'views.myajaxview'),
...

不知道哪里出错了。你能帮我吗?

最佳答案

尽量避免在多个地方写url(遵循DRY原则),可以给一个name to your url ,像这样:

url(r'^getdata_json$', 'views.myajaxview', name='getdata_json')

然后在 HTML 中使用 Django 内置模板标签 url检索 View url:

<table cellpadding="0" cellspacing="0" border="0" id="example1"
data-url="{% url 'getdata_json' %}">

然后在 JS 中你可以使用 jQuery data检索 URL 的方法(而不是对其进行硬编码):

<script type="text/javascript" language="javascript" class="init">
$(document).ready(function() {
$('#example1').dataTable( {
"bServerSide": true,
"sAjaxSource": $(this).data('url'),
"bProcessing": true,
} );
} );
</script>

作为旁注,您可以将 q.nome_struttura 附加到您的 report 数组,在最终数组上使用 json.dumps,如下所示:

for q in query:
report.append(q.nome_struttura)
json = json.dumps(report)

一般来说,当您使用 AJAX 请求时,您应该使用浏览器开发人员工具(例如 Firefox 的 Firebug 或 Chrome 开发人员工具)来准确查看传递给服务器的数据以及响应的方式。

供您引用,有一个 third party Django app完全适合您的用例:将 Django 与 jQuery 数据表与服务器端处理相集成。

关于jquery - Django 数据表加载 ajax 数据加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25975086/

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