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

<?php
setcookie('username','admin');
?>
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>客服功能——客服人员端</title>
  <link rel="stylesheet" href="">
<script>
  var xhr = new XMLHttpRequest();
  //服务器调用函数
  function comet(json){
    var content = '<p style="text-align:left"><span onclick="choose(\''+ json.pos +'\');">' + json.pos + '</span>说:'+json.content+'</p>';
    var old = document.getElementById('chatArea').innerHTML;
    document.getElementById('chatArea').innerHTML = old + content;
  }
  //咨询人选择函数
  function choose(pos){
    document.getElementById('postman').innerHTML = pos;
  }
  //客服人员回复函数
  function resp(){
    var respContent = document.getElementById('respContent').value;
    var pos = document.getElementById('postman').innerHTML;
    if(respContent == '' || pos == ''){
      alert('请重新选择回复人或填写回复内容');
      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="./16-kefu-iframe.php"></iframe>
  <p>咨询人:<span id="postman"></span></p>
  <p><textarea id="respContent"></textarea></p>
  <p><input type="button" value="回复" onclick="resp();" /></p>
</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';
?>


      

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/5299.html