360搜索

作者: pingping_log | 来源:发表于2017-09-20 15:38 被阅读0次

jsonp跨域访问接口
虽然js是受到同源策略,但是引用js文件,img,css文件是不会受到限制的。我们可以利用标签的src属性这个特点,动态的创建script标签,通过src属性发送相关的请求,请求的时候,返回回来的数据,是一个函数调用,会被当作JS代码执行,所以只要我们提前声明好和返回的函数调用同名的函数,那么在数据请求成功之后,

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        * {
            padding: 0;
            margin: 0;
            list-style-type: none;
        }
        .box {
            width: 250px;
            height: 40px;
            border: 1px solid #ccc;
            border-radius: 5px;
            position: absolute;
            top: 100px;
            left: 50%;
            margin-left: -125px;
        }
        .box input {
            height: 100%;
            width: 100%;
            border: none;
            text-indent: 10px;
            outline: none;
        }
        .box ul {
            position: absolute;
            width: 100%;
            top: 40px;
            left: 0;
            border: 1px solid #ccc;
            border-top: none;
            display: none;
        }
        .box ul li {
            height: 40px;
            line-height: 40px;
            border-bottom: 1px solid #ccc;
            text-indent: 10px;
        }
    </style>
</head>
<body>
    <div class='box'>
        <input type="text" placeholder="请输入搜索内容" value="">
        <ul></ul>
    </div>

  <script type="text/javascript" src="art-template.js"></script>

  <script type="text/template" id="tpl">
      {{each result}}
      <li>
        <a href="https://www.so.com/s?ie=utf-8&fr=none&src=home-sug-store&q={{$value.word}}" id="">{{$value.word}}</a>
      </li>
      {{/each}}
  </script>

  <script type="text/javascript">
      window.onload = function () {

                var input = document.querySelector('input');
        var ul = document.querySelector('ul');

        //将这个作为window的属性,这样的话在哪里都可以调用的到
        window.suggest_so = function (data) {
          ul.innerHTML = template('tpl',data);
        }

        input.onkeyup = function () {
          var val = this.value;
          //当输入的值为空的时候隐藏ul
          if(val == "") {
            ul.style.display = "none";
          } else {
            ul.style.display = "block";
          }
          //创建一个script标签,让这个标签发出请求
          var script = document.createElement('script');
          script.src = 'https://sug.so.360.cn/suggest?callback=suggest_so&encodein=utf-8&encodeout=utf-8&format=json&fields=word&word='+val;
          document.body.appendChild(script);
          document.body.removeChild(script);
        }
      }
  </script>

</body>
</html>

相关文章

网友评论

      本文标题:360搜索

      本文链接:https://www.haomeiwen.com/subject/znlosxtx.html