码迷,mamicode.com
首页 > Web开发 > 详细

django+ajax实现在线聊天室

时间:2015-08-31 19:42:02      阅读:230      评论:0      收藏:0      [点我收藏+]

标签:django   ajax   

django+ajax实现在线聊天室


小项目中的一个,就是简单的聊天室
需求:

  • 注册登陆之后才能发言
  • 初始在聊天框中展示最近的消息
  • 发送消息使用ajax,在后台完成消息的存储
  • 使用轮循不断请求get新消息展示在聊天框中

Models

设计聊天消息主题的结构:

class Chat(models.Model):
    sender = models.ForeignKey(User, related_name=‘has_chats‘)
    content = models.TextField()
    time = models.DateTimeField(auto_now_add=True, null=True)

    def __unicode__(self):
        return u‘%s‘ % self.content

Templates

{% extends "base.html" %}
{% block title %}聊天室{% endblock %}
{% block content %}
<!--聊天框-->
<div class="list-group col-md-10 col-md-offset-1 well">
    <div class="list-group-item">
        {% for chat in chats %}
        <h4 class="list-group-item-heading">{{chat.sender}}:{{chat.content}}</h4>
        <p class="list-group-item-text">{{chat.time}}</p>
        <input type="hidden" class="chat_id" value="{{chat.id}}"/>
        <br>
        {% endfor %}
    </div>
</div>
<!--表单-->
<form id="chatForm" class="form-horizontal panel container" method="POST" action=".">{% csrf_token %}
    <div class="form-group col-md-10">
        <textarea type="text" name="content" id="content" value="" class="form-control" id="exampleMessage" placeholder=""></textarea>
    </div>
    <div class="form-group col-md-4">
        <input type="hidden" name="post_type" value="send_chat"/>
        <input type="submit" class="btn btn-lg btn-primary" value="发送"/>
    </div>
</form>
{% endblock %}

js

{% block script %}
<script>
 $(function() {  
    updateMsg();    //更细信息  
            //表单 submit 事件  
    $("#chatForm").submit(function() {  
        //ajax 提交表单  
        $.post("./post/",  
            $(‘#chatForm‘).serialize(),
            function(data) {  
            $("#content").val("");  //消息发送成功后清空内容框  
        });  
        return false;       //阻止表单提交  
    });  
});  

//更新消息  
function updateMsg() {  
    $.post(
        "./post/", 
        {
        post_type: "get_chat",
        last_chat_id: $(".chat_id").last().val()
        }, 
        function(data) {
            $(‘.list-group-item‘).append(data);    //解析返回的 xml  
    });  
    setTimeout("updateMsg()", 1000);        //每秒更新一次  
}  
</script>
{% endblock %}

js部分主要有两块,一个是发送消息,一个是轮循接收
发送消息的部分:把chatForm表单中的信息post到处理页,包括聊天信息内容和post_type,这是我自己定义的一个变量,用于在同一个页面地址处理不同post请求的标示,这里时post_type是send_chat,即发送消息。
更新消息的部分,updateMsg()函数,使用post请求,往相同的地址post数据,内容包括post_type:get_chat,last_chat_id:这是从聊天框获取的最后一条聊天信息的id,$(".chat_id").last().val(),这是为了在获取信息的时候确保是最后一条聊天信息之后的信息,最后设定循环时间为一秒,不断执行。

Views

def index(request):
    chats = list(Chat.objects.all())[-100:]
    return render(request, ‘chatroom.html‘, {‘chats‘: chats})


@csrf_exempt
def post(request):
    if request.method == ‘POST‘:
        post_type = request.POST.get(‘post_type‘)
        if post_type == ‘send_chat‘:
            new_chat = Chat.objects.create(
                content = request.POST.get(‘content‘),
                sender = request.user,
            )
            new_chat.save()
            return HttpResponse()
        elif post_type == ‘get_chat‘:
            last_chat_id = int(request.POST.get(‘last_chat_id‘))
            #print last_chat_id
            chats = Chat.objects.filter(id__gt = last_chat_id)
            return render(request, ‘chat_list.html‘, {‘chats‘: chats})
    else:
        raise Http404
  • index()函数处理聊天主界面,查询数据库中最后100条聊天消息展示在聊天框中
  • post()函数处理接收的聊天消息请求,根据post_type来决定处理动作
    • send_chat:生成一个新Chat实例储存在数据库中,这里可以什么都不返回,因为聊天消息的轮询速度都快,本身就在不断更新消息。
    • get_chat:首先获取last_chat_id,然后通过chats = Chat.objects.filter(id__gt = last_chat_id)这一句来获取id在last_chat_id之后的所有Chat实例,其中filter(id__gt = last_chat_id)的意思是筛选id大于last_chat_id的对象。

完工~

网址戳这里

完整项目github地址

版权声明:本文为博主原创文章,未经博主允许不得转载。

django+ajax实现在线聊天室

标签:django   ajax   

原文地址:http://blog.csdn.net/zhu_free/article/details/48137375

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!