[英]Showing unread count in navbar
所以我目前在views.py中擁有此功能
def live_unread_notification_count(request):
unread_notifications = Notification.objects.all_for_user(request.user).unread().count()
data = {
"unread_notifications": unread_notifications,
}
json_data = json.dumps(data)
return HttpResponse(json_data, content_type='application/json')
print data
我有我的網址
url(r'^notifications/unread_count/$', 'live_unread_notification_count', name='live_unread_notification_count'),
當我到達URL時,我得到正確數量的通知,例如
{"unread_notifications": 2}
當此人刷新頁面時,現在如何在html模板的導航欄中顯示此內容?
我需要一些JavaScript嗎?
請幫忙。
我將使用jQuery進行演示。
首先,為元素提供一個id
,您要在其中顯示通知計數。
例如:
<span id="notifCount"></span>
現在,讓我們進入JS部分:
<!-- Put this code before the body tag ends -->
<!-- Load jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- JS code to fetch notif count -->
<script>
$(document).ready(function() {
$.ajax({
url: '{% url "live_unread_notification_count" %}',
method: 'GET',
success: function(data) {
// assign the count to a variable
var unreadNotifs = data['unread_notifications'];
// put the count in the notifCount element
$('#notifCount').html(unreadNotifs);
}
});
});
</script>
這個答案為您開始使用JS,jQuery和AJAX提供了一個起點。 閱讀這些主題。 待了幾天,您應該就很好了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.