JSONP跨域实现百度搜索框(关键字自动显示)

JSONP跨域的使用流程
1.先声明一个函数,这个函数有一个形参。这个形参会拿到想要下载的数据,可以使用这个形参做后续的数据处理
2.在需要下载数据时,动态创建script标签,将标签的src设置成下载数据的链接
3.当script插入到页面时,就会调用已封装好的函数,将需要的数据传过来

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>百度搜索框</title>
  <style>
    body{
      text-decoration: none;
    }
    #div1 {
      width: 312px;
      height: 200px;
      position: absolute;
      left: 50%;
      top: 50%;
      margin-left: -100px;
      margin-top: -200px;
    }
    #q{
      height: 30px;
      width: 235px;
    }
    #ul1{
      text-decoration: none;
      border: 1px black solid;
      display: none;
      margin-top: 0px;
      width: 200px;
    }
    #ul1 li{
      list-style: none;
      margin-left: -40px;
    }
    #ul1 li a{
      line-height: 30px;
      padding: 5px;
      text-decoration: none;
      color: black;
      display: block;
    }
    #ul1 li a:hover {
      background-color: antiquewhite;
      color: white;
    }
  </style>
  <script>
    function download(data){
      var oUl = document.getElementById("ul1");
      var arr = data.s;
      oUl.innerHTML = "";
      oUl.style.display = "block";
      for(var i=0;i<arr.length;i++){
        var newli = document.createElement("li");
        var oA = document.createElement("a");
        oA.innerHTML = arr[i];
        oA.href = 'http://suggestion.baidu.com/su?wd='+arr[i];
        oA.target = '_blank';
        newli.appendChild(oA);
        oUl.appendChild(newli);
      }
    }
  </script>
  <script>
    window.onload = function(){
      var oQ = document.getElementById("q");
      var oUl = document.getElementById("ul1");
      oQ.onkeyup = function(){
        if(this.value != ''){
          var oScript = document.createElement("script");
          oScript.src = `	http://suggestion.baidu.com/su?wd=${this.value}&cb=download`;
          document.body.appendChild(oScript);
        }else{
          oUl.style.display = "none";
        }
      }
    }
  </script>
</head>

<body>
  <div id="div1">
    <input type="text" id="q">
    <ul id="ul1">

    </ul>
  </div>
</body>

</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值