Javascript JQuery-自动刷新页面的一部分
在Django项目中,我有一个页面,显示特定模型的所有实例。我想每隔几秒钟自动刷新一次页面,但只更新页面的相关部分 我将描述每个部分。首先,我有一个Django的观点。最简单的形式是这样的Javascript JQuery-自动刷新页面的一部分,javascript,jquery,django,Javascript,Jquery,Django,在Django项目中,我有一个页面,显示特定模型的所有实例。我想每隔几秒钟自动刷新一次页面,但只更新页面的相关部分 我将描述每个部分。首先,我有一个Django的观点。最简单的形式是这样的 class MyListView(ListView): lookup_field = 'uuid' model = Foo template_name = 'mylist.html' def get_queryset(self):
class MyListView(ListView):
lookup_field = 'uuid'
model = Foo
template_name = 'mylist.html'
def get_queryset(self):
return list(Foo.objects.all()) # finds all my objects from DB
def get_context_data(self, **kwargs):
objects = self.get_queryset()
context = super(MyListView, self).get_context_data(**kwargs)
context['foos'] = objects # this gets passed to html page
return context
function setup() {
setTimeout("refreshPage();", 5000);
}
function refreshPage() {
window.location = location.href;
}
$(document).ready(setup);
因此,它从数据库中查找所有Foo
对象,并将其返回到html
html页面显示一个表,其中每个条目都是一行。此外,每行的开头都有一个复选框。像这样
<table id="content">
<thead>
<tr>
<th><input type="checkbox" id="chckHead"/></th>
<th>UUID</th>
<th>Attribute1</th>
<th>Attribute2</th>
</tr>
</thead>
<tbody>
{% for item in foos %}
<tr id="{{ item.uuid }}">
<td>
<input type="checkbox" name="checkboxlist" class="chcktbl" />
</td>
<td><code>{{ item.uuid }}</code></td>
<td>{{ item.attribute1 }}</td>
<td>{{ item.attribute2 }}</td>
</tr>
{% endfor %}
</tbody>
</table>
现在,Foo
模型的一些属性可能会在后台得到更新,所以我想用新数据定期刷新页面
我是用javascript做的,就像这样
class MyListView(ListView):
lookup_field = 'uuid'
model = Foo
template_name = 'mylist.html'
def get_queryset(self):
return list(Foo.objects.all()) # finds all my objects from DB
def get_context_data(self, **kwargs):
objects = self.get_queryset()
context = super(MyListView, self).get_context_data(**kwargs)
context['foos'] = objects # this gets passed to html page
return context
function setup() {
setTimeout("refreshPage();", 5000);
}
function refreshPage() {
window.location = location.href;
}
$(document).ready(setup);
所以每5秒钟,JS就会调用refreshPage()
,我的页面就会被刷新。如果数据库在幕后更改,我的页面将反映它
上面的问题是它刷新了整个页面,其中包括复选框。因此,如果我已经选中了一个复选框,刷新会将其重置为原始状态(“未选中”)
那么,解决这个问题的正确方法是什么呢?非常高的层次: 要添加的
窗口.位置
将重置整个页面。到这个时候你已经明白了。您正在寻找的是可以通过使用部分页面或使用REST端点并通过模板将其推回来处理的内容
以下是您希望执行的refreshPage
步骤
我希望这会有所帮助,这是一个非常非技术性的答案,但我不确定我能否在不了解更多项目的情况下给您一个非常具体的答案。是的,如果您这样做,那么javascript就没有那么大的帮助了。您需要再次使用ajax从数据库中获取所有
foos
,并手动更新表内容。这比刷新页面需要更多的工作,但要好得多,这也是使用ajax的全部目的。