AngularJS中的Ajax(聊天机器人)

来源:互联网 发布:php 文件名截断 编辑:程序博客网 时间:2024/06/05 20:37
<!DOCTYPE html><html lang="en"><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 class="chatbox"><!-- 聊天内容 --><div class="messages"></div><!-- 表单 --><div class="form"><!-- 输入框 --><div class="input"><textarea></textarea></div><!-- 按钮 --><div class="btn"><input type="button" value="发送"></div></div></div><script type="text/template"><div class="self"><h5>我说</h5><p>你好</p></div><div class="other"><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>

0 0
原创粉丝点击