簡介
在做“彈幕彈幕”小程序管理員前端時,需要在頁面上不斷更新彈幕列表,方便管理員對彈幕進(jìn)行審核。之前用flask框架可以使用主動推送的方式更新前端頁面,但是Django框架要實現(xiàn)主動推送是比較復(fù)雜的,于是我們最后使用了輪詢的方式進(jìn)行頁面更新。
實現(xiàn)方法
項目架構(gòu)(部分目錄)
.
├── organizer/
| ├── views.py
| └── urls.py
└── templates/
├── barrages_list.html
└── barrages_refresh.html
實現(xiàn)原理
前端頁面通過JQuery定時向后端發(fā)送GET請求,獲取最新的數(shù)據(jù)庫數(shù)據(jù)之后,更新局部頁面的內(nèi)容。
代碼實現(xiàn)
1、barrages_list.html中的主要代碼:
<ul class="list-group" id="barrages_list"></ul>
<script type="text/javascript">
//定時刷新界面(0.5秒)
$(document).ready(function(){
setInterval(function() {
$.get("{% url 'barrages_refresh' %}" + window.location.search,//GET請求的url地址
function(data,status){
$("#barrages_list").html(data);//更新列表內(nèi)容
});
}, 500);
});
</script>
2、barrages_refresh.html中的主要代碼:
{% for barrage in data %}
<li class="list-group-item">
<h4 style="display:inline-block;">{{ barrage.content }}</h4>
<div style="display:inline-block;float:right;">
<button type="submit" class="btn btn-success pass_button" value="{{ barrage.id }}" style="width:100px;margin-right:30px;">通過</button>
<button type="submit" class="btn btn-danger no_pass_button" value="{{ barrage.id }}" style="width:100px;margin-right:30px;">不通過</button>
</div>
</li>
{% endfor %}
3、views.py中的主要代碼:
class BarragesRefresh(APIView):
def get(self):
self.template="organizer/barrages_refresh.html"#渲染的模板
self.check_input('activity_id')
activity_id = self.input['activity_id']
barrages = Barrage.objects.filter(activity_id=activity_id, has_checked_manually=False)
barrages = list(barrages.values("id", "type","content", "openid", "screen_id"))
return barrages
4、urls.py中的主要代碼:
urlpatterns = [
url('barrages/refresh', BarragesRefresh.as_view(),name='barrages_refresh'),
]