一个纯粹基于jQuery和Django的SSE站内信通知的例子

这两天写了一个基于SSE技术的站内信通知红点的例子。现在来总结一下。

首先,站内信红点的实现方式基本上就三种:网页上设置一个Timer然后定时轮询;开一个WebSocket长链接;基于SSE的流模式。最终想试试SSE,就写了这个例子。

其次,SSE的实现也有很多种:第一种基于SSE.js;第二种是PHP;第三种是django。我采用的是django。网上大部分的例子都是需要第三方库: django-sse或者Daphen。我就是想基于原生jQuery和Django来实现。最后找了一个好方法,特此记录一下。

Django端的views代码:

复制代码
def get_unread_message_count_view(request):
    def event_stream():
        while True:
            # 从数据库或其他数据源获取数据
            messages = Messages.objects.filter(read_flag=False)
            unread_message_count = messages.count()
            # 构造SSE消息
            event = 'message'
            message = f'data: {unread_message_count}\n\n'
            yield f'event: {event}\n{message}'

    response = StreamingHttpResponse(event_stream(), content_type='text/event-stream')
    response['Cache-Control'] = 'no-cache'
    return response

urls就是标准的代码

网页端:

复制代码
<div class="fa-stack fa-2x" id="message_bell" data-count="10">
    <i class="fa fa-circle fa-stack-2x"></i>
    <i class="fa fa-bell fa-stack-1x fa-inverse"></i>
</div>
复制代码
<script type="text/javascript">
        $(function () {
            $(document).ready(function() {
            //data根据需求自定义参数
            const eventSource = new EventSource('get_unread_message_count');

            eventSource.addEventListener('message', function(event) {
                const data = event.data;
                $("#message_bell").attr("data-count",data);
                if (data == 0) {
                    $('.fa-stack').addClass('hidden');
                }
                else {
                    $('.fa-stack').removeClass('hidden');
                }
                // 处理收到的数据
            });

            });
        });
    </script>
相关推荐
candyTong18 分钟前
Claude Code 的 Edit 工具是怎么工作的
javascript·后端·架构
GetcharZp1 小时前
GitHub 2.4 万 Star!D2 正在重新定义程序员画图方式
后端
彦为君3 小时前
Agent 安全:从权限提示到沙箱隔离
python·ai·ai编程
zhangxingchao3 小时前
多 Agent 架构到底怎么选?从 Claude Agent Teams、Cognition/Devin 到工程落地原则
前端·人工智能·后端
IT_陈寒3 小时前
SpringBoot那个自动配置的坑,害我排查到凌晨三点
前端·人工智能·后端
ServBay3 小时前
OpenCode 和它的7款必备插件
后端·github·ai编程
ping某3 小时前
逐字节拆解 tcpdump
后端
阿凡9807303 小时前
花 100 dollar,用 Claude 打通 EasyEDA&Fusion 双向同步
后端·程序员
PILIPALAPENG3 小时前
Python 语法速成指南:前端开发者视角(JS 类比版)
前端·人工智能·python