<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Ajax</title> <style> body { margin: 0; padding: 0; background-color: #F7F7F7; } h3 { text-align: center; } .chatbox { width: 500px; height: 500px; margin: 0 auto; border: 1px solid #CCC; background-color: #FFF; border-radius: 5px; } .messages { height: 350px; padding: 20px 40px; box-sizing: border-box; border-bottom: 1px solid #CCC; overflow: scroll; } .messages h5 { font-size: 20px; margin: 10px 0; } .messages p { font-size: 18px; margin: 0; } .self { text-align: left; } .other { text-align: right; } .form { height: 150px; } .form .input { height: 110px; padding: 10px; box-sizing: border-box; } .form .btn { height: 40px; box-sizing: border-box; border-top: 1px solid #CCC; } .form textarea { display: block; width: 100%; height: 100%; box-sizing: border-box; border: none; resize: none; outline: none; font-size: 20px; } .form input { display: block; width: 100px; height: 30px; margin-top: 5px; margin-right: 20px; float: right; } </style> </head> <body> <h3>简单的Ajax实例</h3> <div> <!-- 聊天内容 --> <div> </div> <!-- 表单 --> <div> <!-- 输入框 --> <div> <textarea></textarea> </div> <!-- 按钮 --> <div> <input type="button" value="发送"> </div> </div> </div> <script type="text/template"> <div> <h5>我说</h5> <p>你好</p> </div> <div> <h5>对方说</h5> <p>你好</p> </div> </script> <script> var btn = document.querySelector('.btn'); // 获取输入内容元素 var input = document.querySelector('textarea'); // 聊天窗口 var message = document.querySelector('.messages'); var item = '', result = ''; // 实例 var xhr = new XMLHttpRequest; btn.onclick = function () { // 创建DOM元素 item = createMessage('self', input.value); // 将创建好的DOM元素添加到聊天窗口 message.appendChild(item); console.log(item); // 清空输入框 input.value = ''; // 设置请求行 xhr.open('post', 'chat.php'); // 设置请求头 xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); // 发送请求 xhr.send(); // 监听并处理响应结果 xhr.onreadystatechange = function () { if(xhr.readyState == 4) { // 接收响应结果 result = xhr.responseText; // 创建DOM元素 item = createMessage('other', result); // 将创建好的DOM元素添加到聊天窗口 message.appendChild(item); } } } // 动态创建DOM // flag 代表自已说self 还是对方说other // text 代表说话的内空 function createMessage(flag, text) { // 创建结点 var item = document.createElement('div'), h5 = document.createElement('h5'), p = document.createElement('p'); // 添加类 item.classList.add(flag); // 判断主体 switch(flag) { case 'self': h5.innerText = '我说'; break; case 'other': h5.innerText = '对方说'; break; } // 插入文本 p.innerText = text; // 追加节点 item.appendChild(h5); item.appendChild(p); return item; } </script> </body> </html>
欢迎分享本文,转载请保留出处:前端ABC » AngularJS中的Ajax(聊天机器人)案例