您的位置:永利集团登录网址 > 计算机教学 > thinkphp 实现在线聊天功能的例子

thinkphp 实现在线聊天功能的例子

2019-10-03 17:33

你想为你的博客或者网站添加的在线聊天功能,为你的用户提供技术支持,或者不仅仅是客服功能,让你的用户能够相互交流,增强网站或者博客互动功能,这里为大家介绍1个为博客或者网站打造的聊天工具,只要您懂得thinkphp就能看得懂此段代码。主要实现的方法是thinkphp+ajax,不在赘述直接贴出代码:
数据库结构:
think_msg 表用来存储聊天记录
DROP TABLE IF EXISTS `think_msg`;
CREATE TABLE IF NOT EXISTS `think_msg` (
  `id` int(40) NOT NULL auto_increment COMMENT '信息数目',
  `content` text character set utf8 NOT NULL COMMENT '信息内容',
  `time` int(50) NOT NULL COMMENT '发送信息时间',
  `sender` varchar(20) character set utf8 NOT NULL COMMENT '发送信息人',
  `timee` varchar(20) NOT NULL,
  `tosend` varchar(50) character set utf8 NOT NULL COMMENT '接收人',
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
think_user表 用来存储用户的信息
DROP TABLE IF EXISTS `think_user`;
CREATE TABLE IF NOT EXISTS `think_user` (
  `id` mediumint(6) NOT NULL auto_increment,
  `nickname` varchar(25) NOT NULL,
  `dept_id` smallint(3) NOT NULL,
  `account` varchar(20) NOT NULL COMMENT '账号',
  `pwd` varchar(50) NOT NULL COMMENT '密码',
  `status` int(2) NOT NULL COMMENT '状态:‘0’不在线,‘1’在线,‘2’隐身,‘3’忙碌',
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=4 ;

转载于  

项目中遇到的多条件异步查询及数据分页问题,做了数次尝试,最终虽目的达到,但。。。。。希望能有更好的处理方式

html代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ";
<html xmlns="" xml:lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <title>在线聊天</title>
    <script type="text/javascript" src="/Public/js/jquery.js"></script>
</head>
<style>
    .chat{
        width: 610px;
        height: 422px;
        margin: 0 auto;
        position: relative;
        border: 1px solid #000;
    }
    .show{
        border-bottom: 1px solid #000;
        border-right: 1px solid #000;
        width: 400px;
        height: 300px;
        display: block;
        overflow:auto;
        position:relative;
    }
    .neirong{
       
        display: block;
        margin-top: 5px;
        width: 383px;
        border-bottom:1px dashed #000;
    }
    .nei{
        width: 400px;
        display: block;
    }
    .online{
        width: 200px;
        height: 422px;
        border-left: 1px solid #000;
        position:absolute;
        right:0px;
        top:0px;
    }
    p{
        display: inline;
        width: 400px;
    }
    .one{
        color: blue;
    }
    .neir{
        bottom: 22px;
        position: absolute;
        width: 402px;
        padding-left:1px;
    }
    .fs{
        bottom: 0px;
        position: absolute;
        width: 402px;
        padding-left:1px;
    }
    .submit{
         background-color: blue;
        border: medium none;
        color: #fff;
        float: right;
        line-height: 19px;
        margin-top: 2px;
        cursor: pointer;
        }
    .button{
         background-color: red;
        border: medium none;
        color: #fff;
        float: right;
        line-height: 19px;
        margin-top: 2px;
        margin-left:5px;
        cursor: pointer;
    }
    .option{position:relative;}
    .option ul{height:20px;line-height:20px; margin-top: 2px;padding-left: 9px;}
    .option li{
        float:left;
        list-style:none;
        margin-right: 10px;
    }
    #face1{
        display:none;
        z-index:9999;
        position: absolute;
        top: 326px;
        width:160px;
    }
    #face1 img{
    border: 1px solid #ccc;
    margin-left: 5px;
    cursor: pointer;
    margin-top: 5px;}   
</style>
<body>
    <div><span><a href="{:U(GROUP_NAME.'/Login/logout')}">退出</a></span></div>
    <div class="chat" id="close">
    <!-- 信息展示框 -->
    <div class="show">
        <volist name="msg" id="vo">
            <div class="neirong">
                <span>{$vo.sender}:</span>
                <br>{$vo.content}
            </div>   
        </volist>
    </div>
    <!-- 在线用户框 -->
    <div class="online">
        <span class="neiron">在线会员</span><br />
        <volist name="user" id="vo">
             <a href=""><span class="one">{$value.nickname}</span></a>
        </volist>
    </div>
    <!-- 输入框 -->
    <div class="option">
        <ul>
            <li><a href="javascript:void(0);" id="face" title="表情">^_^</a></li>
        </ul>
    </div>
    <div id="face1">
    [f:1][f:2][f:3][f:4][f:5][f:6][f:7][f:8][f:9][f:10]
    [f:11][f:12][f:13][f:14][f:15][f:16][f:17][f:18][f:19][f:20]
    </div>
    <div class="neir">
        <textarea name="content" class="content" id="content" cols="45" rows="3"  style="width: 394px; height: 70px;"></textarea>
       
    </div>
    <div class="fs">
        <input type="button" class="button" value="关 闭" /><input type="submit" class="submit" value="发 送" />
    </div>
    </div>
</body>
    <script>
    function face_xz(v){
            var facebook='[f:'+v+']';
            var yy=$('#content').val();
            var demo =yy+facebook;
            $('#content').val(demo);
            $('#face1').hide();
        }
    $(document).ready(function(){
        $('.submit').click(function(){
            var name=$('.content').val();
            if(name=="")
            {
                alert("内容不能为空");
            }else
            {
                $.post("{:U(GROUP_NAME.'/Index/ajax')}",{content:name},function(msg){
                    var dat=eval("(" + msg + ")");
                     $(".show").empty();
                     $.each(dat,function(neirongIndex,datt){
                    var html = "<div class='neirong'><span>"+datt['sender'];
                     html += ":</span><br/>"+face_2(datt['content']);
                     html += "</div>";    
                     $('.show').append(html);                                   
                });
                 $("textarea").val('');
                });
            }
        });
        //关闭聊天框
        $('.button').click(function(){
            $('#close').hide();
        });
        /*工具栏*/
        $(document).on('click','#face',function(){
            $('#face1').show();
            $(this).attr("id","gb");
        
        });
        
        $(document).on('click','#gb',function(){
            $('#face1').hide();
            $(this).attr("id","face");
        
        });
        $(function(){
            val=$("#face1").html();
            val=val.replace(/[f:(100|d{1,2})]/g,"<img onclick="face_xz($1)" src='/Public/face/$1.gif'>")
            $("#face1").html(val);
        })
        /**/
    });
    function xx(){
        //返回处理最新十条信息
         $.get("{:U(GROUP_NAME.'/Index/fresh')}",'',function(mess){
             var dat=eval("(" + mess + ")");
             $(".show").empty();
             $.each(dat,function(neirongIndex,datt){
             var html = "<div class='neirong'><span>"+datt['sender'];
              html += ":</span><br/>"+face_2(datt['content']);   
             html += "</div>"; 
                $('.show').append(html);                                     
        });            
             });
             //返回处理在线用户   
         $.get("{:U(GROUP_NAME.'/Index/freshUser')}",'',function(mes){
            var dat=eval("(" + mes + ")");
             $(".one").empty();
             $.each(dat,function(oneIndex,onlin){
                 var line="<a href='' title='点击进行私聊'><span class='one'>"+onlin['nickname']+"<br/></span></a>";
            $('.online').append(line);
    });
    });

  1. <!-- 上传窗口 -->   

  2.     <div id="uploadPicWindow" class="easyui-window" title="上传图片"  style="width:420px;height:220px;padding:20px;background:#fafafa;" data-options="iconCls:'icon-save',closable:true, collapsible:true,minimizable:true,maximizable:true">  

  3.         <form id="picForm" action="" method="post">  

  4.             <div style="margin-bottom:20px">  

  5.                 图片名称:  

  6.                 <input type="text" name="name" id="picName" class="easyui-textbox" style="width:80%" data-options="required:true,validType:'stringCheck'"/>  

  7.             </div>  

  8.             <br/>  

  9.             <div style="margin-bottom:20px">  

  10.                 选择图片:  

  11.                 <input type="file" name="file" id="file" data-options="prompt:'Choose a file...'" style="width:80%"/>  

  12.             </div>  

  13.             <div id="picTip"></div>  

  14.             <div id="formWindowfooterPic1" style="padding:5px;text-align:right;">   

  15.                 <a href="#" onclick="submitPic();" class="easyui-linkbutton" data-options="iconCls:'icon-save'">提交</a>  

  16.             </div>  

  17.         </form>  

  18.     </div>  

基于 tp框架

    }
    //自动刷新
    setInterval("xx()",1000);   
    //处理表情
    function face_2(val){
    val=val.replace(/[f:(100|d{1,2})]/g,"<img src='/Public/face/$1.gif'>")
    return val
    }
    </script>
</html>
php执行代码:
<?php

 

 

    Class IndexAction extends CommentAction{

 前端具体写法

1、html页面代码

        //登陆默认页面,因继承commentAction故不显示

  1. function submitPic(){  

  2.     if(!$("#picForm").form('validate')){  

  3.         return false;  

  4.     }  

  5.     var projectId = $("#projectId").val();  

  6.     var name=$("#picName").val();  

  7.     var type="1";//展示图片  

  8.     var f = $("#file").val();  

  9.     if(f==null||f==""){  

  10.         $("#picTip").html("<span style='color:Red'>错误提示:上传文件不能为空,请重新选择文件</span>");  

  11.         return false;  

  12.       }else{  

  13.        var extname = f.substring(f.lastIndexOf(".")+1,f.length);  

  14.        extname = extname.toLowerCase();//处理了大小写  

  15.        if(extname!= "jpeg"&&extname!= "jpg"&&extname!= "gif"&&extname!= "png"){  

  16.          $("#picTip").html("<span style='color:Red'>错误提示:格式不正确,支持的图片格式为:JPEG、GIF、PNG!</span>");  

  17.          return false;  

  18.         }  

  19.       }  

  20.      var file = document.getElementById("file").files;    

  21.      var size = file[0].size;  

  22.      if(size>2097152){  

  23.           $("#picTip").html("<span style='color:Red'>错误提示:所选择的图片太大,图片大小最多支持2M!</span>");   

  24.           return false;  

  25.       }  

  26.     ajaxFileUploadPic(projectId,name,type);  

  27. }  

  28.   

  29. function ajaxFileUploadPic(projectId,name,type) {  

  30.     $.ajaxFileUpload({  

  31.         url : '${ctx}/projectPic/saveorupdate.jhtml?projectId='+projectId+'&name='+name+'&type='+type, //用于文件上传的服务器端请求地址  

  32.         secureuri : false, //一般设置为false  

  33.         fileElementId : 'file', //文件上传空间的id属性  <input type="file" id="file" name="file" />  

  34.         type : 'post',  

  35.         dataType : 'json', //返回值类型 一般设置为json  

  36.         success : function(data, status) //服务器成功响应处理函数  

  37.         {  

  38.              $("#picList").datagrid('reload');  

  39.              $('#uploadPicWindow').window('close');  

  40.             // alert(data.msg);  

  41.         },  

  42.         error : function(data, status, e)//服务器响应失败处理函数  

  43.         {  

  44.              $("#picList").datagrid('reload');  

  45.              $('#uploadPicWindow').window('close');  

  46.             // alert(data.msg);  

  47.         }  

  48.     });  

  49.     return false;  

  50. }  

  51.  

<div class="h_cityName1">

        public function index(){
            $this->display();
        }

  <div class="h_cityName11">

        //利用ajaxreturn以JSON方式返回聊天内容数组
        public function ajax(){
            $data=array();
            $Model = new Model();
            $data['content']=$_POST['content'];
            $data['time']=time();
            $data['timee']=date('Y-m-d H:i:s',time());
            $data['sender']=session('account');
            $dd=M(msg)->data($data)->add();
            if($dd){
                $dataa=M(msg)->order('id desc')->limit('10')->select();

<span>省</span>

            $this->ajaxReturn($dataa);
           }
        }        

<ul class="h_publicB" id="province_id" name="province_id" >

        //刷新时获取最新十条聊天内容和在线用户
        public function homePage(){
            $this->msg=M(msg)->order('id desc')->limit('10')->select();
            $this->user=M(user)->where(array('status'=>1))->select();
            $this->display();
        }

<volist name="list" id="vo">

        //即时返回最新十条聊天内容
        public function fresh(){
            $data=M(msg)->order('id desc')->limit('10')->select();
            $this->ajaxReturn($data);
        }

<if condition="$areaId eq $vo.areaId">

        //即时返回在线用户
        public function freshUser(){
            $dat=M(user)->where(array('status'=> 1))->select();
            $this->ajaxReturn($dat);
        }

<li value="{$vo.areaId}" onclick="sendData(this,'province_id')"  >{$vo.areaName}</li>

    }
?>

<else />

效果图:

<li value="{$vo.areaId}" onclick="sendData(this,'province_id')"  >{$vo.areaName}</li>

图片 1

</if>

源码下载:

</volist>

   </ul>

</div>

<div class="h_cityName11 h_cityList">

<span>市</span>

<ul class="h_publicB" id="city_id" name="city_id">

</ul>

</div>

   **<div class="h_cityName11 h_areaList" >**

<span>区</span>

<ul class="h_publicB" id="area_id" name="area_id">

</ul>

</div>

</div>

<div class="hangye"><b>行业</b></div>

  **<ul>**

  <volist name="industry" id="industry">

   <li value="" onclick="sendData(this,'industry')" name="{$idfrom_home}" ><span >{$industry.name}</span></li>**    **

   </volist>

   </ul>           

</div>

<div class="search3">

        <input type="text" name="" id="companyname" value=""  placeholder="搜索企业/商户名称"/>

         <a href="#"><input type="submit" class="but1"  id="s-by-c"  onclick="sendData(this,'companyname')" value="" /></a>

 

</div>

<div class="zongmu-lbbu" id="companylist">

<volist name="company" id="vo">

   <div class="recommend-logo" >

      <div class="fl1">

<a href="{:U('Home/Company/detail?id='.$vo['id'])}">

<img src="{$uploads}{$vo.logo}" class="fl-img"/>

<p>{$vo.name}</p>

<span class="span-add">{$vo.addreess}</span>

<img src="{$home_img}qiyezongmu_03.png" class="middle-img"/><span class="span-xx">{$vo.linkman}</span>

<img src="{$home_img}qiyezongmu2_06.png" class="middle-img"/><span class="span-xx">{$vo.linktel}</span>

<img src="{$home_img}qiyezongmu2_03.png" class="middle-img"/><span class="span-xx"> {$vo.qqnum}</span>

</a>

</div>

  <div class="fl2">

<h3>公司主营</h3>

<p>{$vo.des}</p>

</div>

</div>

 </volist>

</div>**       **

 <div class="page" id="page">

<if condition="$arr['count'] neq 0 ">

<span>共<b>{$arr.count}</b>条记录,{$arr.p}/{$arr.Page}页</span>

{$arr.show}

<else />

<center><b>暂无数据</b></center>

</if>

 

</div>

2、jquery & ajax

<script type="text/javascript">

/*

*区域(点击省获取区,点击区获取县)

*/

function sendData(data,type){

var data1=data.value;

var name=$(data).attr('name');

   var companyname=$("#companyname").val();

var data2 =$(data).parent().attr("id");

   var aa = $(data).text();

 $(data).addClass('selectPublicA').siblings().removeClass()

/*ajax post提交返回区域列表 */

$.ajax({ 

url:"{:U('Home/Company/ajaxarea')}",

data:{data:data1,type:type},

type:"post",

dataType:"json",

success:function(msg){

  console.log(msg)

  if(type == 'province_id'){

  var html ='';

  $('#city_id').empty();

  $('#area_id').empty();

  for(var i=0;i<msg.length;i++){

  html += "<li value='"+msg[i].areaId+"' onclick='sendData(this,"city_id")'>"+msg[i].areaName+"</li>";

   }

  $(html).appendTo($("#city_id"));

    }else if(type == 'city_id'){

  $("#area_id").parent().css("display","block");

  var html ='';

  $('#area_id').empty();

  for(var i=0;i<msg.length;i++){

  html += "<li value='"+msg[i].areaId+"' onclick='sendData(this,"area_id")'>"+msg[i].areaName+"</li>"

  }

  $(html).appendTo($("#area_id"));

    **}**

  }

})

$.ajax({

url:"{:U('Home/Company/index')}",

data:{data:data1,type:type,name:name,companyname:companyname},

type:"post",

dataType:"json",

success:function(msg){

console.log(msg)

var html="";

var company=msg.rows;

var url=msg.url;

$('#page').empty(); 

$("#companylist").empty();

if(company != null){

for(var i=0;i<company.length;i++){

html += "<div class='recommend-logo' >"

html += "<div class='fl1'><a href='"+url[i]+"'><img src='{$uploads}"+company[i].logo+"' class='fl-img'/><p>"+company[i].name+"</p>"

html += "<span class='span-add'>"+company[i].addreess+"</span>"

html += "<img src='{$home_img}qiyezongmu_03.png' class='middle-img'/><span class='span-xx'>"+company[i].linkman+"</span>"

html += "<img src='{$home_img}qiyezongmu2_06.png' class='middle-img'/><span class='span-xx'>"+company[i].linktel+"</span>"

html += "<img src='{$home_img}qiyezongmu2_03.png' class='middle-img'/><span class='span-xx'>"+company[i].qqnum+"</span></a></div>"

html += "<div class='fl2'><h3>公司主营</h3><p>"+company[i].des+"</p></div></div>"

}

}

$(html).appendTo("#companylist");

var htmlpage="<span id='page'>共<b>"+msg.count+"</b>条记录,"+msg.p+"/"+msg.Page+"页"+msg.show+"</span>";

$(htmlpage).appendTo($("#page"));

}

})

}

</script>

 

3、PHP 页面

 

public function index(){   

        $p = I('request.p');//获取点击分页的页数

        $paging  = $p<1?1:$p;

   //==============================接收AJAX/GET传参===============//

        $areaId=I('request.data');

        $industryId=I('request.name');

        $type=I('request.type');

        $companyname=I('request.companyname');

   //==============================接收AJAX/GET传参===============//

   //==============================查询条件=====================//

        $map = array('data' => $areaId,'type'=>$type,'name'=>$industryId,'companyname'=>$companyname);

        $order='';

        if(IS_AJAX){

            if($areaId>0){//若点击省市区  该条件写入session

                 $_SESSION['areaId']=$areaId;

                 $_SESSION['type']=$type;

            }

            if($industryId >0){//若点击行业 该条件写入session

                 $_SESSION['industryId']=$industryId;

            }

            if($type == 'industry'){//若点击行业 调用session地区条件

                $areaId=$_SESSION['areaId'];

                $type=$_SESSION['type'];

             }

            if($type == 'companyname'){//若输入企业名查询 调用session 地区、行业条件

                $areaId=$_SESSION['areaId'];

                $industryId=$_SESSION['industryId'];

                $type=$_SESSION['type'];

            }

            $where= $this->get_where($areaId,$type,$industryId,$companyname);

        }else{

            //刷新页面时清除session中条件

            $_SESSION['areaId']="";

            $_SESSION['type']='';

            $_SESSION['industryId']='';

            $where = 'ischeck = 1';

            $where .=" AND ".$this->get_where($areaId,$type,$industryId,$goodsname);

        } 

   //==============================查询条件=====================//

   //==============================查询数据=====================//

   $list =  D('Areas','Api')->getareas(100,1,'*','`parentId`=0');//所有地区列表

        $industry = D('Industry','Api')->getindustry(1000,1,'*','`status`=1 AND `isdelete`=1');//行业信息

   $arr=$this->getData_page('Company',3,'*',$where,$order,$map);

   //==============================查询数据=====================//

         $arr['p']=$paging;

         $company=$arr['rows'];

   if(IS_AJAX){

    echo json_encode($arr);

   }else{

    $this->assign('areaId',$areaId);

            $this->assign('industryId',$industryId);

            $this->assign('company',$company);

            $this->assign('arr',$arr);

            $this->assign('list',$list['tag']);

            $this->assign('industry',$industry['tag']);//需求列表

            $this->display();  

   }

    }

    /*

     * ajax区域联动

     */

 public function ajaxarea(){

        $data['parentId']=$_POST['data'];

        if($_POST['type'] == 'province_id'){

            $list =D('Areas')->getarea($data);

            echo json_encode($list);

        }else if($_POST['type'] == 'city_id'){

            $list =D('Areas')->getarea($data);

            echo json_encode($list);

        }

 

 }

/**

*查询条件处理函数

*/

public function get_where($areaId='',$type='',$industryId='',$companyname=''){

        $where = "1=1";//初始化where变量

        if ( $areaId > 0){

            $where .=" AND {$type}={$areaId}";

        }

        if ($industryId >0){

            $where .= " AND industry_id={$industryId}";

        }

        if ('' != $companyname){

            $where .=" AND `name` LIKE '%{$companyname}%'";

        }

        return $where;

    }

/**

*查询分页数据

*$model 模型名也可视为数据表名

*/

public function getData_page($model,$num='',$field='',$where='',$order ='',$map=''){

        $Model =M($model);

        $num  = ($num != '') ? $num : '10';

        $field  = ($field != '') ? $field : '*';

        if (!empty($field)){

            $Model->field($field);

        } else {

            $Model->field('*');

        }

        if (!empty($where)){

 

            $Model->where($where);

        } 

        if (!empty($order)){

            $Model->order($order);

        }else{

            unset($order);

        }

 

        $count =$Model->where($where)->count();

 

 

        if (!empty($field)){

            $Model->field($field);

        } else {

            $Model->field('*');

        }

        if (!empty($where)){

            $Model->where($where);

        } 

        if (!empty($order)){

            $Model->order($order);

        }

        $Page = new ThinkPage($count,$num);

        $Page->setConfig('prev','上一页');

        $Page->setConfig('next','下一页');

        $Page->setConfig("last",'尾页');

        $Page->setConfig('first','首页');

        $Page->rollPage = '5';

   //TP分页方法 $show 中url 拼接条件参数  点击分页条 除了传P 也会传查询条件参数

        foreach($map as $key=>$val) {

            $Page->parameter[$key]   =   urlencode($val);

        }

        $show = $Page->show();

        $offset = $Page->firstRow.','.$Page->listRows;

        $Model->limit($offset);

        $rows = $Model->select();

        $pagetotal =ceil($Page->totalRows/$num);

        $pagetotal<1 ? 1:$pagetotal;

        $arr =array('count'=>"$count",'Page'=>"$pagetotal",'show'=>"$show",'rows'=>$rows);

        return $arr;

    }

 

总结:ajax获取条件参数提交给 php,php分情况存SESSION,以保证下个条件查询时拥有之前的条件;分页部分利用tp自带分页查询,在此基础上 将ajax提交的参数拼接到每次点击分页后的URL 再通过get获取即可实现异步查询后的数据分页

 

本文由永利集团登录网址发布于计算机教学,转载请注明出处:thinkphp 实现在线聊天功能的例子

关键词: