【发布时间】:2022-01-28 21:00:26
【问题描述】:
我有一段代码使用 AJAX 调用每 5 秒刷新一次 HTML 表格
我基本上是清空 HTML 表格,然后每 10 秒再次附加所有数据以实现此目的
类似的东西-
$('#_appendHere').html('')
$('#_appendHere').append(response);
其中_appendHere 是表的id 属性
这是我的 HTML 代码 - (数据正在从我的 Django 视图传递到此页面)
<body>
<div>
<div>
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names..">
</div>
</div>
<br>
<br>
<br>
<br>
<table id="_appendHere" class="table table-striped table-condensed">
<tr>
<th>Username</th>
<th>Email</th>
<th>Gender</th>
</tr>
{% for item in info_data %}
<tr>
<td>{{item.username}}</td>
<td>{{item.email}}</td>
<td>{{item.gender}}</td>
</tr>
{% endfor %}
</table>
</body>
CSS -
<style>
table, td, th {
border: 1px solid #ddd;
text-align: left;
}
table {
border-collapse: collapse;
width: 100%;
}
th, td {
padding: 15px;
}
</style>
这是 javascript 部分 -
var append_increment = 0;
setInterval(function() {
$.ajax({
type: "GET",
url: {% url 'App1:tempPage' %}, // URL to your view that serves new info
data: {'append_increment': append_increment},
})
.done(function(response) {
$('#_appendHere').html('')
$('#_appendHere').append(response);
append_increment += 10;
});
}, 5000)
在呈现同一页面的 Django 视图中对该 URL 发出 GET 请求 -
from django.contrib import admin
from django.urls import path,include
from App1 import views
app_name = 'App1'
urlpatterns = [
path('temp/', views.tempPage,name="tempPage"),
]
views.py 文件 -
from django.shortcuts import render
from App1.models import Info
# Create your views here.
def tempPage(request):
info_data = Info.objects.all()
context={"info_data":info_data}
return render(request, 'App1/temp1.html', context)
由于某种原因,这段代码也附加了输入标签(搜索框)……但只执行一次
我不知道为什么会这样
我尝试将 input 标记放在不同的 div 中,但这也是同样的事情
任何帮助将不胜感激!谢谢!!
【问题讨论】:
-
我们需要查看更多代码,以及响应中返回的 get 调用是什么。
-
ajax调用返回的HTML是什么?这是向我们展示的关键部分。
-
我已经添加了 get 请求正在获取的 url。它是我正在渲染的 django 视图
标签: javascript html jquery css ajax