//用jsonp模拟百度搜索
```<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
padding: 0;
margin: 0;
}
li {
list-style: none;
}
a {
color: inherit;
text-decoration: none;
}
img {
vertical-align: top;
}
.w {
width: 1140px;
margin: 0 auto;
}
.searchBox {
display: flex;
height: 45px;
margin-top: 20px;
}
.searchBox .searchBtn {
width: 120px;
}
.searchBox .searchCon {
flex: 1;
outline: none;
resize: none;
}
.list {
line-height: 32px;
text-indent: 1em;
}
.list li {
border: 1px dashed #000;
}
.list li:not(:first-child) {
border-top: 0;
}
</style>
</head>
<body>
<div class="wrap w">
<div class="searchBox">
<input type="text" class="searchCon"></input>
<input type="button" value="搜索" class="searchBtn">
</div>
<div class="list">
<!-- <li><a href="">hello</a></li>
<li><a href="">hello</a></li>
<li><a href="">hello</a></li>
<li><a href="">hello</a></li>
<li><a href="">hello</a></li>
<li><a href="">hello</a></li>
<li><a href="">hello</a></li>
<li><a href="">hello</a></li>
<li><a href="">hello</a></li>
<li><a href="">hello</a></li> -->
</div>
</div>
</body>
<script>
// 百度搜索接口 https://www.baidu.com/sugrec?pre=1&p=3&ie=utf-8&json=1&prod=pc&from=pc_web&sugsid=33515,33357,33273,31660,33594,33570,33392,33591,33267&wd=h556&req=2&csor=4&pwd=h55&cb=jQuery1102049450989307729043_1614849843077&_=1614849843081
// 简化版
// https://www.baidu.com/sugrec?prod=pc&wd=h5&cb=fn
// prod=pc PC端
// wd=h5 搜索的关键词
// cb= 回调函数名
// {
// g: [{}, {}, {}] // 搜索的数据集合
// }
var listBox = document.querySelector(".list");
var searchCon = document.querySelector(".searchCon");
var searchBtn = document.querySelector(".searchBtn");
searchCon.oninput = function () {
var key = searchCon.value.trim();
// 随机函数名
// jQuery1102049450989307729043_1614849843077
// Date.now() 构造函数的方法 返回当前时间对应的毫秒数 (时间戳)
var fnName = "Jsonp" + String(Math.random()).substr(2) + "_" + Date.now();
console.log(fnName); // 字符串
// 如何动态查找 => 此事件触发在页面加载之后 此时已经有了fn
// 动态的创建script 放到head中(放到页面时才会请求 => 触发函数fn)
var script = document.createElement("script");
script.src = `https://www.baidu.com/sugrec?prod=pc&wd=${key}&cb=${fnName}`;
document.head.appendChild(script);
// 函数中声明的函数也是局部的 => 如何改全局 => window.fn => window["fn"]
window[fnName] = function (data) {
console.log(data);
var { g } = data;
if (g) { //有数据
var html = "";
g.forEach(function ({ q }) {
html += `<li><a href="https://www.baidu.com/s?ie=UTF-8&wd=${q}">${q}</a></li>`
})
listBox.innerHTML = html;
} else { //没有数据
listBox.innerHTML = "";
}
// 等请求完成之后 删除对应的script标签(卸磨杀驴)
if (script) {
script.remove();
}
}
}
</script>
<!-- fn({}) -->
<!-- <script src="https://www.baidu.com/sugrec?prod=pc&wd=h5&cb=fn"></script> -->
</html>
用jsonp数据模拟百度搜索
最新推荐文章于 2021-12-16 17:55:03 发布