postpass 使用JSONP+防抖实现360搜索 – 个人博客

使用JSONP+防抖实现360搜索

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>360搜索</title>
    <style>
      * {
        box-sizing: border-box;
        margin: 0px;
        padding: 0px;
      }

      li {
        list-style: none;
      }
    </style>
  </head>
  <body>
    <div>
      <input type="text" id="keywords" />
      <button>提交</button>
    </div>
    <ul id="pushli"></ul>

    <script>
      //防抖函数
      function fd(fn, delay) {
        let timer = null;
        let _this = this;
        return function () {
          if (timer != null) clearTimeout(timer);
          let args = Array.from(arguments);
          timer = setTimeout(() => {
            fn.apply(_this, args);
          }, delay);
        };
      }

      //jsonp回调处理
      function getInfo(obj) {
        let result = obj.result;
        document.querySelector("#pushli").innerHTML = "";
        result.forEach((element) => {
          document.querySelector(
            "#pushli"
          ).innerHTML += `<li>${element.word}</li>`;
        });
      }

      //jsonp
      function getKeyWords(value) {
        let url =
          "https://sug.so.360.cn/suggest?callback=getInfo&encodein=utf-8&encodeout=utf-8&format=json&src=so_home&fields=word&word=" +
          value;

        if (document.querySelector("#sc")) {
          document.body.removeChild(document.querySelector("#sc"));
        }

        let script = document.createElement("script");
        script.id = "sc";
        script.src = url;
        document.body.appendChild(script);
      }

      //创建防抖
      let listenKeyWords = fd(getKeyWords, 500);

      //监听键盘事件,使用防抖
      document.querySelector("#keywords").onkeyup = function () {
        let value = document.querySelector("#keywords").value;
        if (!value) return;
        listenKeyWords(value);
      };
    </script>
  </body>
</html>

标签

发表评论