学了ajax得到了一个图灵机器人的链接,写了一个和机器人对话的效果,现在分享一下。
HTML和style代码
<style> *{margin:0; padding:0; list-style:none;} #outer{width: 720px;margin: 50px auto 0; background: #CCCCCC;padding: 20px;} #con{width: 700px;height: 30px;padding: 0 10px; font-size: 20px; margin-bottom: 20px;} #talk{overflow: hidden;} #talk li{font-size: 16px; line-height: 150%;} #talk .me{background: #8c8c8c;text-align: right; color: blue;} #talk .pc{color: #46b8da;} </style>
<div id="outer"> <input type="text" id="con"/> <ul id="talk"> </ul> </div>js部分的代码
<script> var con = document.getElementById('con'); var talk = document.getElementById('talk'); document.onkeyup = function (e) {//键盘事件监听回车键 var ev = e || event; if(ev.keyCode == 13){ if(con.value == ''){ alert('内容不能为空!'); }else{ sendMsg(); con.value = ''; } } } function sendMsg(){ var newLi = document.createElement('li'); newLi.className = 'me'; newLi.innerHTML = 'me:'+con.value; talk.appendChild(newLi); var xhr = null;//新建一个变量来存储ajax对象 if(window.XMLHttpRequest){//创建ajax对象兼容写法来兼容一般浏览器和ie浏览器 ajax链接第一步 xhr = new XMLHttpRequest(); }else{ xhr = new ActiveXObject('Microsoft.XMLHTTP'); } //拼接url var Url='http://www.tuling123.com/openapi/api?key=fb6b7bcfbe52fccdb7f5d752a3088f75&info='+con.value+'&userid=1234567'; xhr.open('get',Url,true);//打开和服务器链接 使用get方法异步传送 xhr.send();//发送信息 xhr.onreadystatechange = function () {//监测链接状态 if(xhr.readyState == 4){//判断是否是链接最后一个阶段 if(xhr.status == 200){//判断是否链接成功 /*解析返回的信息*/ var str = JSON.parse(xhr.responseText); var newLi2 = document.createElement('li'); newLi2.className = 'pc'; newLi2.innerHTML = 'pc:'+str.text; talk.appendChild(newLi2); }else{ alert(xhr.status); } } } } </script>感觉挺好玩的,感兴趣可以试一试。