1. 程式人生 > >原生js利用圖靈機器人實現自動回覆功能

原生js利用圖靈機器人實現自動回覆功能

HTML程式碼:

<style type="text/css">
		* {
			padding: 0;
			margin: 0;
		}

		.imgLayout {
			width: 100%;
			height: 100%;
			margin: 0 auto;
			padding: 1px;
		}

		.outer {
			box-sizing: border-box;
			width: 600px;
			height: 600px;
			border-radius: 20px;
			background-color: whitesmoke;
			border: 2px solid white;
			margin: 20px auto;
			padding: 5px;
		}

		.chatContent {
			box-sizing: border-box;
			width: 100%;
			height: 480px;
			overflow: auto;
			margin-bottom: 10px;
		}

		.outer input {
			width: 580px;
			height: 45px;
			font-size: 30px;
			line-height: 45px;
		}

		.outer button {
			width: 580px;
			height: 45px;
			font-size: 30px;
			line-height: 45px;
			background-color: cornflowerblue;
			border-radius: 20px;
			margin-top: 5px;
			margin-bottom: 5px;
			outline: cornflowerblue;
		}

		.outer .chatContent div {
			width: 550px;
			display: none;
		}

		.outer .chatContent .msg_mine {
			text-align: right;
			float: right;
			margin-right: 5px;
		}

		.outer .chatContent .msg_robot {
			clear: both;
		}

		.chatContent img {
			width: 40px;
			height: 40px;
			border-radius: 50%;
		}
	</style>

<div class="imgLayout">
		<div class="outer">
			<div class="chatContent">
				<div class="msg_robot">
					<img src="robot.jpg" alt="robot">
					<p></p>
				</div>
				<div class="msg_mine">
					<img src="myself.jpg" alt="myself">
					<p></p>

				</div>
			</div>
			<input type="text">
			<button class="send_btn">Send</button>
		</div>
	</div>

js邏輯程式碼

var robot = (function () {
			return {
				init(ele) {
					this.ele = document.querySelector(ele);
					this.input = this.ele.querySelector('input');
					this.send = this.ele.querySelector('.send_btn');
					this.msg_robot = this.ele.querySelector('.msg_robot');
					this.msg_mine = this.ele.querySelector('.msg_mine');
					this.chatContent = this.ele.querySelector('.chatContent');
					this.event();

				},
				event() {
					var that = this;
					this.send.onclick = function () {
						console.log('151')
						that.chat;
					}
					document.onkeydown = function (e) {
						if (e.keyCode == 13) {
							that.chat();
						}
					}
				},
				chat() {
					var that = this;
					var sayContent = this.input.value;
					var paras = "key=7e0c61672f674208a85f85f7ff08855f&userid=robot&info=" + sayContent;
					ajax.post("http://www.tuling123.com/openapi/api", paras, function (content, xhr) {
						var newNodeMine = that.msg_mine.cloneNode(true);
						newNodeMine.lastElementChild.innerHTML = sayContent;
						newNodeMine.style.display = 'block';
						that.chatContent.appendChild(newNodeMine);
						that.autoScroll(that.chatContent);
						that.input.value = '';
						console.log(content)
						var obj = JSON.parse(content);
						var msgRoot = obj.text;
						//判斷圖片資訊
						if (obj.url) {
							msgRobot += "<a href='" + obj.url + "' target='_blank'>點我看圖片.</a>";
						}
						//判斷菜譜資訊
						if (obj.list && obj.code == "308000") {
							msgRobot += " ①菜譜名字:" + obj.list[0].name + " ②菜譜原料:" + obj.list[0].info + " 做飯連結:" + "<a href='" + obj.list[0].detailurl + "' target='_blank'>點我看怎麼做?</a>";
						}
						//判斷新聞資訊
						if (obj.list && obj.code == "302000") {
							msgRobot += " ①文章標題:" + obj.list[0].article + " ②文章來源:" + obj.list[0].source + " 做飯連結:" + "<a href='" + obj.list[0].detailurl + "' target='_blank'>點我看新聞.</a>";
						}
						var newNodeRoot=that.msg_robot.cloneNode(true);
						newNodeRoot.lastElementChild.innerHTML=msgRoot;
						newNodeRoot.style.display='block';
						that.chatContent.appendChild(newNodeRoot);
						that.autoScroll(that.chatContent)
					})
				},
				autoScroll(content) {
                  setTimeout(function step(){
					  var top=content.scrollTop;
					  content.scrollTop+=top+4;
					  if (top==content.scrollTop) {
						  setTimeout(step,20)
					  }
				  },0)
				}
			}
		}())
robot.init('.imgLayout');

myAjax.js封裝:

//一個ajax物件
var ajax = {
    get:function (url,successCallBack,failCallBack) {
        var xhr = new XMLHttpRequest();
        xhr.open("GET",url,true);
        xhr.onreadystatechange = function () {
            //xhr.readyState 的值有0 1 2 3 4
            if(xhr.readyState == 4){
                //判斷xhr.status的響應碼
                if(xhr.status == 200 || xhr.status == 304){
                    //判斷successCallBack 是否傳遞了一個函式
                    if(typeof successCallBack == "function"){
                        //將xhr.responseText的資訊交給使用者回撥函式處理
                        successCallBack(xhr.responseText,xhr);
                    }else if(typeof failCallBack == "function"){
                        //將xhr.responseText的資訊交給使用者回撥函式處理
                        failCallBack(xhr.responseText,xhr);
                    }
                }
 
            }};
        xhr.send(null);
    },
    post:function (url,data,successCallBack,failCallBack) {
        var xhr = new XMLHttpRequest();
        xhr.open("POST",url,true);
        xhr.onreadystatechange = function () {
            //xhr.readyState 的值有0 1 2 3 4
            if(xhr.readyState == 4){
                //判斷xhr.status的響應碼
                if(xhr.status == 200 || xhr.status == 304){
                    //判斷successCallBack 是否傳遞了一個函式
                    if(typeof successCallBack == "function"){
                        //將xhr.responseText的資訊交給使用者回撥函式處理
                        successCallBack(xhr.responseText,xhr);
                    }else if(typeof failCallBack == "function"){
                        //將xhr.responseText的資訊交給使用者回撥函式處理
                        failCallBack(xhr.responseText,xhr);
                    }
                }
 
            }};
        //設定請求頭,這行程式碼,一定要在open之後, send之前呼叫.
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.send(data);
    }
};