django+ajax實現線上聊天室,djangoajax

來源:互聯網
上載者:User

django+ajax實現線上聊天室,djangoajax
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_exemptdef 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地址

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.