搜索引擎
+ 能实现使用百度家的服务器, 是因为人家的服务器确实是按照 jsonp 的规则书写
+ 查看百度的搜索引擎接口
+ https://www.baidu.com/sugrec?
pre=1&
p=3&
ie=utf-8&
json=1&
prod=pc&
from=pc_web&
sugsid=34305,34099,33970,34273,34278,34004,34281,34107,34111,26350,22159&
wd=ab&
req=2&
csor=2&
cb=jQuery1102019930028420068102_1627023610760&
_=1627023610785
<div class="box">
<input type="text">
<button>小灰狼一下</button>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
<li>10</li>
</ul>
</div>
const inp = document.querySelector('input')
const ul = document.querySelector('ul')
// 1. 绑定 input 事件
inp.oninput = function () {
// 2. 拿到输入的文本内容
const text = this.value.trim()
// 3. 发送请求请求数据了
// 动态创建一个 script 标签
const script = document.createElement('script')
// 给 script 标签设置 src 属性
script.src = `https://www.baidu.com/sugrec?pre=1&p=3&ie=utf-8&json=1&prod=pc&from=pc_web&sugsid=34305,34099,33970,34273,34278,34004,34281,34107,34111,26350,22159&wd=${ text }&req=2&csor=2&cb=fn&_=1627023610785`
// 把 script 标签插入到 body 里面
document.body.appendChild(script)
// 这个 script 标签插入到页面以后, 请求发送出去
// 回来的时候, 一定会执行代码, script 标签已经没有用了
script.remove()
}
// 把返回的函数定义在全局
// 因为后端返回的是 'fn()' 这一段代码就是调用全局 fn 函数
function fn(res) {
// 4. 根据后端返回的 res 渲染页面
// console.log(res)
// 只有返回的 res 内有一个叫做 g 的数组存在的时候
// 说明当前的关键字有相关的内容, 此时才渲染
// 否则就不渲染了
if (!res.g) {
// 说明没有 g 这个数组
ul.classList.remove('active')
return
}
// 代码执行到这里, 说明有内容需要渲染
let str = ''
res.g.forEach(item => {
str += `<li>${ item.q }</li>`
})
// 插入到 ul 内部
ul.innerHTML = str
// 让 ul 显示
ul.classList.add('active')
}
* {
margin: 0;
padding: 0;
}
.box {
width: 650px;
height: 60px;
border: 1px solid #333;
position: relative;
display: flex;
margin: 50px auto;
}
input, button {
outline: none;
border: none;
}
.box > input {
width: 450px;
padding-left: 50px;
line-height: 60px;
font-size: 30px;
}
.box > button {
flex: 1;
font-size: 20px;
cursor: pointer;
}
.box > ul {
position: absolute;
width: 650px;
padding: 20px;
box-sizing: border-box;
border: 1px solid #333;
border-top: none;
top: 100%;
left: 0;
display: none;
}
.box > ul.active {
display: block;
}
.box > ul > li {
list-style: none;
height: 30px;
line-height: 30px;
font-size: 20px;
cursor: pointer;
}
.box > ul > li:hover {
background-color: #ccc;
color: #fff;
}