实现前端消息发送到后台
(也就是1发的消息到web server)
前端消息发送到后台主要采用ajax
首先需要捕捉键盘,执行Enter键就发消息。
这里采用的是一个jquery的方法进行绑定,捕捉Enter键
//抓取回车键,发送消息,把消息发送到后台
$("body").delegate("textarea","keydown",function(hpy){
if(hpy.which == 13){
var msg_text = $("textarea").val();
if($.trim(msg_text).length > 0){
console.log(msg_text);
//发送消息到后台
SendMsg_hpy(msg_text);
}
//消息添加到对话框的里
AddSentMsgIntoBoxhpy(msg_text);
$("textarea").val('')
}
});
用自定义的SendMsg_hpy方法把消息发送到后台,定义一个字典,保存数据。
用ajax的方法把消息post到后台。(此处需要用将字典转换成json发送后台,不然python无法识别js字典)
//利用ajax把消息发送到后台,时间由服务器端收到加上
//信息包括由谁发送,发给谁,消息内容和发送方式,群发还是个人
//前端消息发送到后端(web server)
function SendMsg_hpy(msg){
//js字典python无法识别,把字典转换成json发到后台,后台在反序列化提取
var msg_dic={
'from_id': "{{ request.user.userprofilehpy.id }}",
'to_id':$(".dialog-box-head span").attr("contact-id"),
'contact_type':$(".dialog-box-head span").attr("contact-type"),
'msg':msg
}
//用ajax post
//或者,post发送消息
//callback_hpy返回值
//function(callback_hpy)回调函数
//post,加验证处理csrf跨站
$.post("{% url 'chat_send_msg' %}",{'data':JSON.stringify(msg_dic),'csrfmiddlewaretoken':$("input[name='csrfmiddlewaretoken']").val()},function(callback_hpy){
console.log(callback_hpy);
})
}
在urls.py加上chat_send_msg的路由
url(r'^send_msg/$', views.send_msg,name='chat_send_msg')
在定义views.py
defsend_msg(request):
print(request.POST)
data = request.POST.get('data')
并且用AddSentMsgIntoBoxhpy方法把消息添加到对话框去,并且在自己的对话框页面展示出来,实现一个发送消息自动下滑的效果。
//前端消息添加到对话框里面,并且在自己的对话框展示出来
function AddSentMsgIntoBoxhpy(msg_text){
//自己发的消息在右边,别人发的在左边
//pull right bootstrap的样式,切换在右边
//拼字符串
var msg_div_hpy = "<div style='padding:18px' class='row'><div class='pull-right'>"+
"<span>"+"{{ request.user.userprofilehpy.name }}" + "</span>"+
"<span>"+new Date().toLocaleTimeString()+"</span>"+
"<p>"+msg_text+"</p>"+"</div></div>";
$(".dialog-box-content").append(msg_div_hpy);
//做一个向下的动画效果,把新发的消息放在最下面
$(".dialog-box-content").animate({
scrollTop:$(".dialog-box-content")[0].scrollHeight},500
);
}