我正在Django中开发代码并尝试自动刷新表。我使用过jquery,但它没有刷新表。 以下是我的观点:(views.py)
from django.http import HttpResponse
from django.template import loader
from models import objectDB
def index(request):
objects= objectDB.objects.all()
template = loader.get_template('Myapp/index.html')
context= { 'objects': objects}
return HttpResponse(template.render(context, request))
def refreshedindex(request):
increment = int(request.GET['increment'])
increment_to = increment + 10
objects= objectDB.objects.all()
template = loader.get_template('Myapp/refreshedindex.html')
context= {'objects': objects}
return HttpResponse(template.render(context, request))
这是我的表加上java脚本:(index.html)
<style>
#customers {
font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
border-collapse: collapse;
width: 100%;
}
#customers td, #customers th {
border: 1px solid #ddd;
padding: 8px;
}
#customers tr:nth-child(even){background-color: #f2f2f2;}
#customers tr:hover {background-color: #ddd;}
#customers th {
padding-top: 12px;
padding-bottom: 12px;
text-align: left;
background-color: #4CAF50;
color: white;
}
</style>
{% if objects %}
<table style="width:100%" border="1" id = "customers">
<tr>
<th>obj Value</th>
<th>item</th>
<th>Type</th>
<th>Tags</th>
<th>Date First</th>
<th>Date Last</th>
</tr>
{% for obj in objects %}
<tr>
<td>{{ obj.value }}</td>
<td>{{ obj.item }}</td>
<td>{{ obj.type }}</td>
<td>{{ obj.tags }}</td>
<td>{{ obj.date_first }}</td>
<td>{{ obj.date_last }}</td>
</tr>
{% endfor%}
</table>
{% else %}
<h3>These is no obj to show</h3>
{% endif %}
<script type="text/javascript" src="jquery-1.11.3.min.js"></script>
<script>
var append_increment = 0;
setInterval(function() {
$.ajax({
type: "GET",
url: {% url 'refreshedindex' %}, // URL to your view that serves new info
data: {'append_increment': append_increment}
})
.done(function(response) {
$('#customers').append(response);
append_increment += 10;
});
}, 10000)
</script>
以下是页面更新时需要使用的代码(refreshedindex.html)
{% for obj in objects %}
<tr>
<td>{{ obj.value }}</td>
<td>{{ obj.item }}</td>
<td>{{ obj.type }}</td>
<td>{{ obj.tags }}</td>
<td>{{ obj.date_first }}</td>
<td>{{ obj.date_last }}</td>
</tr>
{% endfor%}
这是url.py的代码。
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name= 'index'),
url(r'^$', views.refreshedindex, name= 'refreshedindex'),
]
我试图解决这个问题,但我不知道这里有什么问题。你能帮我解决这个问题吗?