jsonp实现百度搜索框功能

由于ajax的同源策略,我们无法跨域请求数据,但是jsonp技术很好地解决了这个问题。本文利用百度搜索框接口结合jsonp技术实现获取百度关键字数据并完成百度搜索框功能:


我们可以直接在百度的搜索框上获取到它的接口,比如我们点击百度搜索文本框的时候,在chrome的network里可以看到它向一个url发起了请求,这个url也就是我们所需要的接口

把这个url取出来:https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=&json=1&p=3&sid=&req=2&sc=eb&csor=0&cb=jQuery110202521957712722107_1553828892769&_=1553828892771

去除一些我们不需要的参数,最终得到https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=&cb=jQuery110202521957712722107_1553828892769

其中wd表示我们要搜索的关键字,cb是百度规定的回调函数,我们尝试把wd赋值为汉字“中”,

即:https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=中&cb=jQuery110202521957712722107_1553828892769

然后用浏览器打开

可以看到服务器返回了一个函数的调用,jQuery110202521957712722107_1553828892769是函数名字,里面的参数是一段json数据。

基于这些,我们可以自己写一个jsonp的代码来实现这个功能


简单的样式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<style>
* {
padding: 0;
margin: 0;
list-style: none;
text-decoration: none;
}
a{
display: block;
color: black;
width: 100%;
}
a:hover{
background-color: rgb(172, 220, 235);
}
a:visited{
color: black;
}
.wrapper {
width: 400px;
position: absolute;
left: 50%;
margin-left: -200px;
margin-top: 200px;
}

input {
height: 34px;
width: 400px;
}

ul {
display: none;
width: 400px;
border: 1px solid #ccc;
}
</style>

<body>
<div class="wrapper">
<input type="text">
<ul>
</ul>
</div>
</body>


关键的jsonp代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<script>
oUl = document.getElementsByTagName('ul')[0];
oInput = document.getElementsByTagName('input')[0];
oInput.oninput = function () {
var value = this.value;

var oScript = document.createElement('script');
oScript.src = "https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=" + value + "&cb=doJson";
document.body.appendChild(oScript);
document.body.removeChild(oScript);//用完就删,拔吊无情
}

function doJson(data) {
var s = data.s;
var str = "";
if (s.length > 0) {
s.forEach(function (ele, index) {
if(index<5){
// 只显示5行
str += ("<li><a href=https://www.baidu.com/s?wd="+ele+" target=_block>" + ele + "</a></li>");
}
});
oUl.innerHTML = str;
oUl.style.display = "block";
}else{
oUl.style.display = "none";
}

}

</script>



(完)