ajax实现百度搜索输入动态获取数据

来源:互联网 发布:mmd动作数据怎么导入 编辑:程序博客网 时间:2024/06/17 11:55

这里简单的利用ajax原理来模拟百度的搜索,实现边输入边动态的获取服务器的数据。

1、HTML页面布局

<html>     <head>    <meta charset="UTF-8">    <title></title>      </head>     <body>         <input type="text" name="txt" id="txt" value="" />         <ul id="ul">         </ul>      </body></html>

2、style样式页面

<style>input{    width: 300px;    height: 30px;}ul{    list-style: none;    width: 300px;       padding: 0;    margin:0;    border: 1px solid #ccc;         display: none;              }ul li{    list-style: none;    width: 300px;    height: 30px;    line-height: 30px;          }ul li a{    display: block;    color: #333;    text-decoration: none;}ul li a:hover{    background: #ccc;}</style>

3、javascript代码

<script>function fn(data){    console.log(data)    var oUl=document.getElementById('ul');    var arr=data.s;             var html="";    for(var i=0;i<arr.length;i++){                  html+='<li><a href="https://www.baidu.com/baidu?tn=monline_3_dg&ie=utf-8&wd='+arr[i]+'" target="_blank">'+arr[i]+'</a></li>';    }    oUl.innerHTML=html;}</script><script>    window.onload=function(){    var oUl=document.getElementById('ul');    var oTxt=document.getElementById('txt');    var oHead=document.getElementsByTagName('head')[0];    oTxt.onkeyup=function(){        var oS=document.createElement('script');//动态添加script标签    oS.src='https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd='+oTxt.value+'&cb=fn';//从百度获取的接口数据    oHead.appendChild(oS);    if(oTxt.value!=''){         oUl.style.display='block';    }else{        oUl.style.display='none';        }    }}</script>
阅读全文
0 0
原创粉丝点击