我有一个Web应用程序,用户可以在其中搜索相机列表,搜索将在HTML表中返回相机。这是我要添加的功能:
这是我当前的代码,它取决于用户按下Enter键的时间。
<!-- siren_search.html -->
<div class="row">
<div class="col-sm-8 col-md-7 col-xl-5 mx-auto">
<form id="searchform" action="{% url 'siren_search' %}" method="GET">
<input id="searchbar" name="query" autocomplete="off" onkeyup=getCameras(this.value) placeholder="Search for the name of a jobsite."
class="form-control" type="search" />
</form>
</div>
</div>
<div class="row">
<div id="results-section" class="col-sm-8 col-md-7 col-xl-5 mx-auto">
{% if cameras.count > 0 %}
<button id="trigger-all-btn" type="button" class="btn btn-lg btn-block btn-outline-danger btn-space js-trigger-all-sirens-btn">Trigger
all sirens</button>
<table id="camera-table" class="table table-hover">
<thead>
<tr class="header">
<th scope="col" style="width:33%;">Asset Name</th>
<th scope="col" style="width:33%;">Job Site</th>
<th scope="col" style="width:33%;"></th>
</tr>
</thead>
<tbody>
{% for camera in cameras %}
<tr>
<td>{{ camera.asset_name }}</td>
<td>{{ camera.site.name }}</td>
<td><button type="button" id="{{ camera.asset_name }}-siren-btn" class="btn btn-outline-danger float-right js-single-trigger-btn">Siren</button></td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
{% endif %}
</div>
</div>
# views.py
def siren_search(request):
context = {}
if request.is_ajax():
term = request.GET.get('query')
if term:
try:
jobsite = JobSite.objects.get(name__icontains = term)
cameras = jobsite.camerasystem_set.all()
context = {
'cameras': cameras,
}
except ObjectDoesNotExist:
return JsonResponse({'success': False}, 400)
return JsonResponse({'context': context}, 200)
else:
term = request.GET.get('query')
if term:
try:
jobsite = JobSite.objects.get(name__iexact = term)
cameras = jobsite.camerasystem_set.all()
context = {
'cameras': cameras,
}
except ObjectDoesNotExist:
pass
return render(request, 'siren_search.html', context)
// search.js
function getCameras(query) {
$.get('?query=' + query, query, searchSuccess(query))
}
function searchSuccess(response) {
console.log(response)
// Display table results HTML. Do I do this from here in Javascript or read
// from a template file like ajax_search.html?
}
这是主屏幕上的样子:
这是每次击键时应保持的外观,并不断更新表格,并且仅当jobsite
对于所有摄像机都相同时,才显示“触发所有警报”按钮。
我的问题是:
在按下Enter键时添加AJAX表HTML而不与表HTML冲突的最Python方式是什么?我要从JsonResponse()
返回一个views.py
并用Javascript创建表格吗?我是否返回文件ajax_template.html
并让javascript将HTML附加到siren_search.html
的正文中?