大家好,我成功创建了一个无需更新即可更新表的ajax,但是我的问题是ajax每次运行时都会追加相同的结果。我的问题是,我该如何解决这个问题,以便ajax仅将新结果附加到表中,而不是一次又一次地将相同结果附加到表中?
人们告诉我使用.html方法,但我不认为我想要的是因为如果使用此方法,它将把整个显示更改为get_more_table.html
destination.html
{% load staticfiles %}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<title>Hello, world!</title>
</head>
<body>
<table id="_appendHere" class="table table-striped table-condensed">
<tr>
<th>name</th>
<th>desc</th>
<th>status</th>
<th>price</th>
</tr>
{% for i in dest %}
<td>{{ i.name|upper }}</td>
<td>{{ i.desc|capfirst }}</td>
<td>{{ i.status|capfirst }}</td>
<td>{{ i.price | capfirst}}</td>
</tr>
{% endfor %}
</table>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"
integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49"
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.min.js"
integrity="sha384-o+RDsa0aLu++PJvFqy8fFScvbHFLtbvScb8AjopnFD+iEQ7wo/CG0xlczd+2O/em"
crossorigin="anonymous"></script>
<script>
function updateTable(){
console.log("hello")
$.ajax({
method: "GET",
url: "get_more_table",
success: function(data) {
console.log(data)
$("#_appendHere").append(data);
}
})
}
var interval = setInterval(function () {
updateTable();
}, 10000);
</script>
</body>
</html>
视图
def record_table(request):
dest = Destination.objects.all()
return render(request,"destination.html",{'dest':dest})
def get_more_table(request): <--- my callback table
dest = Destination.objects.all()
return render(request,"get_more_table.html",{'dest':dest})
get_more_table.html
{% for i in dest %}
<td>{{ i.name|upper }}</td>
<td>{{ i.desc|capfirst }}</td>
<td>{{ i.status|capfirst }}</td>
<td>{{ i.price | capfirst}}</td>
</tr>
{% endfor %}
只需在ajax成功函数内创建表行,然后使用.html()
删除先前的数据并添加新的数据。此外,在行的开头也缺少<tr>
进行添加。因此,在ajax下的代码成功函数如下所示:
//your 1st row
var datas="<tr><th>name</th><th>desc</th> <th>status</th><th>price</th></tr>";
datas += data;//appending data coming from php
$("#_appendHere").html(datas);