PHP使用反向Ajax技术实现在线客服系统( 二 )


      return;
    }
    //ajax提交请求
    xhr.open('POST','16-kefu-sendmsg.php',true);
    xhr.setRequestHeader('Content-Type','Application/x-www-form-urlencoded');
    xhr.onreadystatechange = function (){
      if(this.readyState == 4 && this.status == 200){
        if(this.responseText == 'ok'){
          //回复成功,把回复信息显示到聊天界面中
          var content = '<p style="text-align:right">你回复'+ pos + ':'+respContent+'</p>';
          var old = document.getElementById('chatArea').innerHTML;
          document.getElementById('chatArea').innerHTML = old + content;
          document.getElementById('respContent').value = '';//给回复内容重新置空
        }
      }
    }
    var sendData = 'rec=' + pos + '&content='+respContent;
    xhr.send(sendData);
  }  </script>
<style>  #chatArea{
    width:500px;
    height:400px;
    border:1px solid black;
    overflow: scroll;
  }</style>
</head>
<body>
  <h1>客服功能——客服人员端</h1>
  <h2>原理:iframe+长连接</h2>
  <div id="chatArea">
  </div>
  <iframe width="0" height="0" frameborder="0" name="frame" src=https://www.isolves.com/it/cxkf/yy/php/2020-04-18/"./16-kefu-iframe.php">
  <p>咨询人:<span id="postman"></span></p>
  <p><textarea id="respContent"></textarea></p>
  <p><input type="button" value=https://www.isolves.com/it/cxkf/yy/php/2020-04-18/"回复" onclick="resp();" />


</body>
</html> 发送咨询/回复消息(16-kefu-sendmsg.php)
主要是接受信息,把数据写入到数据库中
<?php
/**
 * 客服回复咨询人,咨询人咨询客服
 * @author webbc
 */
header('Content-type:text/html;charset=utf-8');
require('./conn.php');
$rec = $_POST['rec'];//咨询人变为接收者
$pos = $_COOKIE['username'];//客服人员变为发送者
$respContent = $_POST['content'];//客服人员的回复内容
$sql = "insert into msg (pos,rec,content) values ('$pos','$rec','$respContent')";
echo MySQL_query($sql) ? 'ok':'fail';
?>
 客户人请求咨询信息(16-kefu-iframe.php)
主要功能是保持连接永不断开,然后不断的从数据库读取一条未读的咨询消息,如果有消息,先设置该消息为已读,返回js脚本,影响iframe的父窗体
<?php
/**
 * 通过iframe来实现反向Ajax
 * @author webbc
 */
header('Content-type:text/html;charset=utf-8');
set_time_limit(0);//设置页面永久执行
//ob_start();//打开输出缓存过了,就不需要使用此函数了
//由于浏览器是根据内容大小才先显示,可以先显示4000个空白字符串让浏览器可以继续显示
echo str_repeat(' ', 4000),"<br/>";
ob_flush();
flush();
while(true){
  //从数据库读取一条未读的咨询消息
  require('./conn.php');
  $sql = "select * from msg where rec = 'admin' and isread = 0 limit 0,1";


推荐阅读