搜索后django刷新div元素
Posted
技术标签:
【中文标题】搜索后django刷新div元素【英文标题】:django refresh div element after search 【发布时间】:2021-10-11 19:44:09 【问题描述】:我正在尝试创建一个 todoapp,当我搜索一个单词时它会显示表格而不刷新整个页面。
这是我的 index.html
<body>
<h2>My Personal TodoApp Project</h2>
<br>
<form action="/searchlist/" method="get">%csrf_token%
<input type="text" name="content" placeholder="Search a todolist" class="form-control">
<input class="button button2" type="submit" name="submit" value="Search"/>
</form>
# where i want my table diplay after searching a particular word
<div id="list"></div>
<script type="text/javascript">
$.ajax(
var url = '/templates/searchlistdiv/',
$('#list).show();
var div = $('#list');
div.load(url);
)
</script>
</body>
还有我的观点.py
def searchtodolist(request):
if request.method == 'GET':
query = request.GET.get('content', None)
if query:
results = Todoitem.objects.filter(content__contains=query)
return render(request, 'searchlistdiv.html', "results": results)
return render(request, 'searchlistdiv.html')
最后是我的 searchlistdiv.html
<table>
<tr>
<th colspan="2">List of Todos</th>
</tr>
% for result in results %
<tr>
<td>result.content</td>
<td><form action="/deleteTodo/todo_items.id/" style="display: inline; " method="post">
%csrf_token%
<input class="button button1" type="submit" value="Delete"/>
</form></td>
</tr>
% endfor %
</tr>
</table>
我 100% 确定我的 js 缺少一些东西,我只是不知道我真的不打算学习 js,但仍试图专注于后端开发部分(也许将来我会学习前端)
【问题讨论】:
【参考方案1】:你可以这样做:
<form id="form_id" action="" method="get">%csrf_token%
<input type="text" name="content" placeholder="Search a todolist" class="form-control">
<input class="button button2" type="submit" name="submit" value="Search"/>
</form>
<script>
$("#form_id").submit(function (e)
e.preventDefault(); //this is what i use do prevent default action. [send request without refreshing the whole page]
var serializedData = $(this).serialize();
$.ajax(
type: 'GET',
url: "% url '/searchlist/' %", //url to your view.
data: serializedData,
success: function (response)
$("#list").html(response.searchlistdiv); // Where $("#list") is the container of "searchlistdiv"
,
error: function (response)
alert('Error');
)
)
</script>
在你的views.py中:
from django.template.loader import render_to_string
from django.http import JsonResponse
def searchtodolist(request):
if request.method == 'GET':
query = request.GET.get('content', None)
if query:
results = Todoitem.objects.filter(content__contains=query)
d_partner_html = render_to_string("searchlistdiv.html", "results": results, request)
return JsonResponse('searchlistdiv': d_partner_html)
return render(request, 'searchlistdiv.html')
【讨论】:
感谢您的回答,似乎它在做某事但是没有显示我添加了 searchdiv.html以上是关于搜索后django刷新div元素的主要内容,如果未能解决你的问题,请参考以下文章