请选择 进入手机版 | 继续访问电脑版

如何通过ajax实现百度搜索输入动态获取数据方法教程

[复制链接]
查看1496 | 回复0 | 2020-11-12 21:53 | 显示全部楼层 |阅读模式
如何通过ajax实现百度搜索输入动态获取数据方法教程
这里简单的利用ajax原理来模拟百度的搜索,实现边输入边动态的获取服务器的数据。
1、HTML页面布局

  1. <html>
  2.      <head>
  3.     <meta charset="UTF-8">
  4.     <title></title>
  5.       </head>
  6.      <body>
  7.          <input type="text" name="txt" id="txt" value="" />
  8.          <ul id="ul">
  9.          </ul>
  10.       </body>
  11. </html>
复制代码
2、style样式页面
  1. <style>
  2. input{
  3.     width: 300px;
  4.     height: 30px;
  5. }
  6. ul{
  7.     list-style: none;
  8.     width: 300px;   
  9.     padding: 0;
  10.     margin:0;
  11.     border: 1px solid #ccc;     
  12.     display: none;         
  13.     }
  14. ul li{
  15.     list-style: none;
  16.     width: 300px;
  17.     height: 30px;
  18.     line-height: 30px;      
  19.     }
  20. ul li a{
  21.     display: block;
  22.     color: #333;
  23.     text-decoration: none;
  24. }
  25. ul li a:hover{
  26.     background: #ccc;
  27. }
  28. </style>
复制代码
3、javascript代码
  1. <script>
  2. function fn(data){
  3.     console.log(data)
  4.     var oUl=document.getElementById('ul');
  5.     var arr=data.s;         
  6.     var html="";
  7.     for(var i=0;i<arr.length;i++){              
  8.     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>';
  9.     }
  10.     oUl.innerHTML=html;
  11. }
  12. </script>
  13. <script>
  14.     window.onload=function(){
  15.     var oUl=document.getElementById('ul');
  16.     var oTxt=document.getElementById('txt');
  17.     var oHead=document.getElementsByTagName('head')[0];
  18.     oTxt.onkeyup=function(){   
  19.     var oS=document.createElement('script');//动态添加script标签
  20.     oS.src='https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd='+oTxt.value+'&cb=fn';//从百度获取的接口数据
  21.     oHead.appendChild(oS);
  22.     if(oTxt.value!=''){
  23.         oUl.style.display='block';
  24.     }else{
  25.         oUl.style.display='none';
  26.         }
  27.     }

  28. }
  29. </script>
复制代码
欢迎测试,本人亲测没问题。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

UID
1
贡献
387
丢币
38902
主题
4607
回帖
116
注册时间
2018-9-25
最后登录
2024-3-24