我有一个 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)。
一种常见的方法是使用 jQueryajax() http://api.jquery.com/jquery.ajax/方法向服务器发送 ajax 请求,使用 django 应用程序处理此请求,将响应发送回客户端,然后操作 DOM。
所以你的客户端代码需要
- send an XMLHttp请求 https://developer.mozilla.org/en/docs/Web/API/XMLHttpRequest到服务器(通常使用$.ajax() http://api.jquery.com/jquery.ajax/)
- 修改 DOM,如果
请求成功(通常在$.ajax() http://api.jquery.com/jquery.ajax/成功回调
功能)
- 您可以通过迭代 JSON 响应中的数据来创建表行所需的标记,然后使用 JavaScript/jQuery 将前一行替换为这个新标记(如图所示)here https://stackoverflow.com/questions/7517519/using-jquery-replace-one-row-in-table-with-a-new-one)
你的 django 应用程序需要
- 匹配 a 中的 URL 模式URL调度程序 https://docs.djangoproject.com/en/dev/topics/http/urls/
- 在关联视图中查询数据库
- 将返回的数据序列化为JSON https://stackoverflow.com/questions/383692/what-is-json-and-why-would-i-use-it(你可以使用PythonJSON https://docs.python.org/2/library/json.html module)
- 通过 a 返回此 JSONHttpResponse https://docs.djangoproject.com/en/dev/ref/request-response/#httpresponse-objects (这个问题 https://stackoverflow.com/questions/2428092/creating-a-json-response-using-django-and-python讨论 JSON 和 HttpResponses)
我也推荐你阅读这个优秀的答案 https://stackoverflow.com/questions/20306981/how-do-i-integrate-ajax-with-django-applications关于使用 django 和 ajax(包括 jQuery 的示例)$.ajax() http://api.jquery.com/jquery.ajax/方法)。
还值得一提的是,您不必在 ajax 步骤中使用 jQuery -您可以使用纯 JavaScript 生成 Ajax 请求 https://stackoverflow.com/questions/8567114/how-to-make-an-ajax-call-without-jquery- 然而这是一种流行的方法并且非常用户友好。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)