我有一个 Django 模板,它显示从数据库接收到的多个值并将其传递给模板,如下所示:
在 views.py 中
def test1(requests):
requests.get...
requests.get...
requests.get...
someQuery = "select id from table;"
executeQ(someQuery)
someQuery = "select id from table;"
executeQ(someQuery)
someQuery = "select id from table;"
executeQ(someQuery)
context = Data1, Data2, Data3
return render_to_response('test1/index.html', context)
在模板/test1/index.html
<html>
......
<table>
<th> header1 </th>
<th> header2 </th>
<th> header3 </th>
{% for row in context %}
<td> row.1 </td>
<td> row.2 </td>
<td> row.3 </td>
{% endfor %}
现在,我想要的是通过 Ajax 更新那些 row.1、row.2、row.3,而无需每次都重新加载页面。数据来自数据库。那么我可以在哪里以及如何放入一些 Ajax() 以便 Django 发生这种情况?
最佳答案
除了服务器端代码 (Python) 之外,您还需要添加一些客户端代码 (JavaScript)。
一种常见的方法是使用 jQuery ajax()
向服务器发送 ajax 请求的方法,使用您的 django 应用程序处理此请求,将响应发送回客户端,然后操作 DOM。
所以你的客户端代码需要
- 发送XMLHttpRequest到服务器(通常使用
$.ajax()
) - 如果
请求成功(通常在
$.ajax()
成功回调中 功能) - 您可以通过遍历 JSON 响应中的数据来创建表格行所需的标记,然后使用 JavaScript/jQuery 将前一行替换为这个新标记(如图所示 here )
你的 django 应用程序需要
- 匹配 URL dispatcher 中的 URL 模式
- 在关联 View 中查询您的数据库
- 将返回的数据序列化为JSON (你可以使用 python JSON 模块)
- 通过
HttpResponse
返回此 JSON (this SO question 谈论 JSON 和 HttpResponses)
我还建议您阅读 this excellent answer关于使用 django 和 ajax(包括 jQuery $.ajax()
方法的示例)。
还值得一提的是,您不必为 ajax 步骤使用 jQuery - you can generate Ajax requests with pure JavaScript - 然而,这是一种流行的方法并且非常用户友好。
关于jquery - 如何从 Ajax() 获取值到 Django 模板中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23838975/