获取百度关键词联想API JSONP跨域获取百度搜索词提示下拉列表功能
以下是百度关键词联想的API地址:
https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=笨牛&json=1&p=3&cb=Aralic&t
那怎么读取这些联想词呢,我们要知道一点,我们向百度发起的访问,是属于跨域资源请求,所以是不能直接使用AJAX获取的,但是百度是支持JSONP调用的,因此可以通过这个方式读取。
我们看看这个完整调用参数
参数 值
wd 关键字
json 1
p 3
cb 回调函数
html代码:
<div id="container"> <input type="text" id="kw"> <ol id="dataList"> </ol></div>
javascript 部分:
问题和功能实现大致分为六部分:
1、什么时候请求数据或者触发请求数据的条件是什么?
2、怎么去请求数据?
3、数据怎么格式处理?
4、处理的数据怎么放到页面中?
5、实现键盘上下按键切换下拉提示
6、enter按键打开新页面,跳转到搜索结果
解决方案:
1、我能说针对问题1我就去查资料了吗?
在input搜索内,可以添加的键盘事件按时间分别为onkeydown<onkeypress<onkeyup. 如果不通过判断输入的键值码,那么为了得到搜索框内刚输入的值,就只能用onkeyup事件了,不然无法获取刚刚输入的值。
2、请求数据方法,激动人心的时刻到了,到贴代码了。
//按键抬起事件function getData() { //下拉提示列表
var oDataList = $(‘#dataList‘); //搜索框
var sInput = $(‘#kw‘); var oldValue = null; //当前文本框的值不为空 且和之前不相同
if (sInput.value != ‘‘ && sInput.value != oldValue) { //创建script标签
var oScript = document.createElement(‘script‘); //获取时间戳
var oTime = new Date().getTime()
oScript.src = ‘https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=‘+(sInput.value)+‘&json=1&p=3&cb=Aralic&oTime‘;
document.body.appendChild(oScript);
} else if (sInput.value == ‘‘) { // 如果文本框值为空 清除oDataList的内容并隐藏
oDataList.style.display = ‘none‘;
oDataList.innerHTML = "";
}
oldValue = sInput.value;
}
3、数据的处理,这是jsonp请求的数据,所以需要在全局新建一个一个函数。参数为data(jsonp发送来的数据);
可以直接从chrome开发者工具,网络下找到请求,然后右侧有个Preview可以预览返回的数据,当然也有更简单的一个格式化方法
直接在函数里面控制台打印数据,这样阅读格式化的数据了。


返回了一个json数据,q表示搜索关键字,s是数组类型,返回的匹配值。
4、数据的处理并且添加到页面中。
//jsonp的回调函数function Aralic(data) {
console.log(data); var oDataList = $(‘#dataList‘); var sInput = $(‘#kw‘); var str = ‘‘; var iNow = -1;
//当有数据返回时
if (data.s.length) { //拼接字符串
for (var i = 0; i<data.s.length; i++) {
str += ‘<li><a href="https://www.baidu.com/s?wd=‘+data.s[i]+‘" target=_blank>‘+data.s[i]+‘</a></li>‘;
}
oDataList.style.display = ‘block‘;
oDataList.innerHTML = str; //↑ ↓ 两个按键事件
document.onkeydown = function(ev) { var ev = ev || window.event; var aLi = oDataList.getElementsByTagName(‘li‘); //↓键
if (ev.keyCode == 40) { for (var i = 0; i<aLi.length; i++) {
aLi[i].className = ‘‘;
}
iNow ++; if (iNow == aLi.length) {
iNow = 0;
} //移除给文本框的绑定事件
removeEvent(sInput, ‘keyup‘, getData);
sInput.value = data.s[iNow];
aLi[iNow].className = "active";
} else if (ev.keyCode == 38) { for (var i = 0; i<aLi.length; i++) {
aLi[i].className = ‘‘;
}
iNow = iNow -1; if (iNow == -1) {
iNow = aLi.length - 1;
}
removeEvent(sInput, ‘keyup‘, getData);
sInput.value = data.s[iNow];
aLi[iNow].className = "active";
}
document.onkeyup = function() { //重新绑定事件
addEvent(sInput, ‘keyup‘, getData);
}
} //无数据返回时候 ul内容置空并隐藏
} else {
oDataList.style.display = ‘none‘;
oDataList.innerHTML = "";
}
}5、按键的上下移动控制下拉提示列表。中间出了一个问题,困扰我好长时间。
最开始,我给输入框一个键盘抬起事件,如果当前输入框的值改变,那么我去请求新数据。
然后我实现键盘控制下拉提示列表,并同时把选中的下拉提示列表更新到输入框中。诡异的事情发生了,文本框的值只要一改变,立马请求新数据
下拉提示列表重新被渲染,我去百度首页看百度的效果,上下按键控制更新到输入框的值并不会重新去请求数据。
后来仔细分析找到原因了,因为焦点还在输入框里面,并且上下按键虽然是给document绑定的事件,但是盖不住事件捕捉啊。所以文本框的值也被改变了。
鉴于此,我对文本框的按键抬起事件进行了绑定,当触发按键上下键(onkeydown事件)移动选中下拉提示的时候,移出文本框的绑定事件,当鼠标抬起的时候我又
重新绑定事件,好机智有木有!
6、如何按enter打开搜索结果页?
浏览器对超链接有默认行为,不需要单独添加enter事件,在获取数据页面渲染的时候,对a的地址进行赋值,地址是https://www.baidu.com/s?wd=keyword
附一份聚合搜索代码
可以实现关键词联想的,搜索框;集合了百度,谷歌,搜狗,360,腾讯等多家搜索
search.html的代码:
<!doctype html>
<html>
<head>
<title>搜索框例子</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="./js/jquery-2.1.3.min.js"></script>
<script type="text/javascript" src="./js/keyword.js"></script>
<link href="./css/search.css" rel="stylesheet" type="text/css">
<style type="text/css">
*{margin:0 auto}
</style>
</head>
<body>
<!--start search-->
<div id="search_bg" style="margin-top:20px;margin-bottom:20px;">
<div id="button_bg">
<div>
<span>站内搜索</span>
<span>百度搜索</span>
<span>360搜索</span>
<span>腾讯搜索</span>
<span>搜狗搜索</span>
<span>谷歌搜索</span>
</div>
<span></span>
<form action="http://www.baidu.com/s" method="GET" target="_blank" >
<input type="text" value="" x-webkit-speech="" placeholder="点击搜索" name="wd" autocomplete="off"><!--autocomplete 屏蔽输入自动记录-->
<input type="submit" name="sub" value="百度一下">
</form>
<div></div>
</div>
</div>
<!--end start-->
</body>
</html>
search.css的代码如下:
/*---------------------搜索框样式-------------------------------*/
#search_bg{
width: 960px;
height:50px;
}
#search_bg #button_bg .seach_type{
display: block;
width: 80px;
height: auto;
padding: 0px;
border: solid 1px rgba(204,204,204,0.5);
position: absolute;
top:45px;
left: 20px;
display: none;
z-index: 21;
}
#search_bg #button_bg .seach_type .type{
display: block;
width: 80px;
height: 26px;
background: rgba(255,255,255,0.3);
border-bottom:dashed 1px #cccccc;
text-align: center;
line-height:26px;
cursor: pointer;
}
#search_bg #button_bg .seach_type .type:hover{
color: #126AC1;
}
#search_bg #button_bg .changetype{
display: block;
width: 8px;
height: 12px;
position: absolute;
top:20px;
left: 30px;
cursor: pointer;
background: url(../images/class_1_16_1.png);
}
#search_bg #button_bg{
width:600px;
height: 50px;
position: relative;
}
#search_bg #button_bg .textb{
display: block;
width: 400px;
height: 36px;
outline: none;
background: none;
border:solid 1px #CCCCCC;
float:left;
margin-top:5px;
margin-left:20px;
text-align: left;
text-indent: 20px;
font-size: 15px;
}
#search_bg #button_bg .subb{
display: block;
width: 80px;
height: 40px;
outline: none;
border: none;
background: #1F76CB;
float: left;
margin-top:5px;
cursor: pointer;
box-shadow: 0 1px 2px rgba(28,116,203,0.5);
color: #ffffff;
font-size: 15px;
text-shadow:0 1px 2px rgba(245,247,250,0.2);
}
#search_bg #button_bg .textb:focus{
border:solid 1px #1F76CB;
}
#search_bg #button_bg .subb:hover{
box-shadow: 0 1px 3px rgba(28,116,203,1);
}
#search_bg #button_bg .keyword{
width: 400px;
height: auto;
border:solid 1px #cccccc;
border-top:none;
position: absolute;
top:45px;
left:20px;
z-index:40;
box-shadow: 1px 2px 2px rgba(5,5,5,0.1);
display: none;
}
#search_bg #button_bg .keyword span{
display: block;
clear: both;
width: 400px;
height: 30px;
text-indent:15px;
line-height: 30px;
cursor: pointer;
background: rgba(255,255,255,0.3);
border-bottom:dashed 1px #cccccc;
}
#search_bg #button_bg .keyword span:hover{
background: rgba(0,0,0,0.5);
}
/*------------------seach结果集样式---------------------*/
#search_result{
width: 960px;
height: auto;
min-height: 400px;
overflow: hidden;
}
#search_result .result_num{
width: 960px;
height: 26px;
text-align: left;
text-indent: 15px;
font-size: 15px;
line-height: 26px;
color:#767676;
}
#search_result .result{
width: 960px;
height: auto;
max-height: 110px;
margin-top:15px;
margin-bottom: 15px;
padding-top: 15px;
padding-bottom: 15px;
text-indent: 20px;
line-height: 25px;
color: #333333;
text-overflow: ellipsis;
overflow: hidden;/*以上三行实现溢出显示省略号*/
border-bottom:dashed 1px #cccccc;
}
#result_page{
width: 960px;
height: 30px;
}
#result_page a{
display: block;
float: left;
margin-left:5px;
width: 30px;
height: 30px;
text-align: center;
text-decoration: none;
line-height: 30px;
background: none;
color: #363636;
border:solid 1px #A5A5A5;
transition:all .5s linear;
-webkit-transition: al.5s linear;/* Safari and Chrome or liebao*/
-moz-transition: all .5s linear;/*Firefox */
-o-transition: all .5s linear;/*Opera */
-ms-transition: all .5s linear;/*for ie*/
}
#result_page a:hover{
color:#0A67C1;
border:solid 1px #0A67C1;
}
#result_page .nowpage{
border:solid 1px #EAE8E8;
color:#0F9512;
}
#result_page .previous,
#result_page .next{
width: 80px;
height: 30px;
}
keyword.js的代码如下:
$(document).ready(function(){
/*--------------------搜索框样式控制js------------------------*/
var checktype=$("#search_bg #button_bg .changetype");
var type=$("#search_bg #button_bg .seach_type .type");
var seach_type=$("#search_bg #button_bg .seach_type");
var form=$("#search_bg #button_bg form");
var textb=$("#search_bg #button_bg form .textb");
var subb=$("#search_bg #button_bg form .subb");
var tbcolor="#126AC1";
textb.focus();//文档加载完毕 搜索框获取焦点
var search_types={
"types":[{name:"wd",action:"./search.php",value:"搜索本站",subcolor:"#126AC1",stype:"./images/sanjiao_03.png"},
{name:"wd",action:"http://www.baidu.com/s",value:"百度一下",subcolor:"#126AC1",stype:"./images/sanjiao_03.png"},
{name:"q",action:"http://www.so.com/s",value:"360搜索",subcolor:"#53C920",stype:"./images/sanjiao_04.png"},
{name:"w",action:"http://www.soso.com/q",value:"腾讯搜索",subcolor:"#760AAA",stype:"./images/sanjiao_05.png"},
{name:"query",action:"http://www.xuan369.com/so/qqkk8.jsp",value:"搜狗搜索",subcolor:"#F94F1B",stype:"./images/sanjiao_06.png"},
{name:"q",action:"http://209.85.228.42/search",value:"谷歌搜索",subcolor:"#29C971",stype:"./images/sanjiao_07.png"}
]};
//alert(search_types.types[1].value);
//选择搜索类型按钮被点击
checktype.click(function(){
seach_type.css({"display":"block",height:0});
seach_type.animate({
height:(type.height()+1)*type.length,
},500);
});
type.click(function(){
//alert(search_types.types[$(this).index()].value)
form.attr("action",search_types.types[$(this).index()].action);//改变表单提交位置
textb.attr("name",search_types.types[$(this).index()].name);//改变表单变量名
subb.val(search_types.types[$(this).index()].value);//改变按钮显示
subb.css({background:search_types.types[$(this).index()].subcolor});//改变按钮颜色
tbcolor=search_types.types[$(this).index()].subcolor;//改变输入框边框颜色
checktype.css({"background":"url("+search_types.types[$(this).index()].stype+")"});
subb.css({"box-shadow":"0 1px 2px "+search_types.types[$(this).index()].subcolor});
textb.focus();//编辑框获取焦点
seach_type.animate({
height:0,
},500,function(){
seach_type.css({"display":"none",height:0});
});
});
seach_type.mouseleave(function(){
seach_type.animate({
height:0,
},500,function(){
seach_type.css({"display":"none",height:0});
});
});
textb.focus(function(){
textb.css({border:"solid 1px "+tbcolor});
//
seach_type.animate({
height:0,
},500,function(){
seach_type.css({"display":"none",height:0});
});
});
textb.blur(function(){
textb.css({border:"solid 1px "+"#CCCCCC"});
});
/*-----------------获取关键词js---------------------*/
var textb=$("#search_bg #button_bg form .textb");
textb.keyup(function(event){
if(textb.val()==""||textb.val()==" "){
return;
}
if(event.which!=39&&event.which!=40&&event.which!=37&&event.which!=38&&event.which!=13)
$.ajax({
url:"http://suggestion.baidu.com/su",
type:"GET",
dataType:"jsonp",
jsonp: 'jsoncallback',
async: false,
timeout: 5000,//请求超时
data:{
"wd":textb.val(),
"cb":"keydata"
},
success: function (json) {
},
error: function (xhr) {
return;
}
});
});
});
//打印关键词
function keydata(keys){
var len=keys.s.length;
var keywordbox=$("#search_bg #button_bg .keyword");//关键词盒子
var textb=$("#search_bg #button_bg form .textb");
var subb=$("#search_bg #button_bg form .subb");
if(len==0){
keywordbox.css({display:"none"});
}else{
keywordbox.css({display:"block"});
}
var spans="";
for(var i=0;i<len;i++)
{
spans+="<span>"+keys.s[i]+"</span>"
}
keywordbox.html(spans);//把关键词写入关键词盒子
keywordbox.animate({
height:(keywordbox.children().height()+1)*len//关键词下滑效果
},100);
//点击候选词汇
keywordbox.children().click(function(){
textb.val($(this).html());//选中词汇放入输入框
keywordbox.animate({
height:0//关键盒子收缩效果
},10,function(){
keywordbox.css({display:"none",height:"auto"});
keywordbox.empty();//清空盒子内容
});
textb.focus();//输入框获取焦点*/
$("#search_bg #button_bg form").submit();//提交搜索
});
//提交按钮获取焦点后
subb.focus(function(){//提交按钮获取焦点后
keywordbox.animate({
height:0//关键盒子收缩效果
},10,function(){
keywordbox.css({display:"none",height:"auto"});
keywordbox.empty();//清空盒子内容
});
});
/*textb.blur(function(){//输入框失去焦点后收缩关键词盒子(此方法会与点击候选词方法冲突造成失效)
keywordbox.animate({
height:0//关键盒子收缩效果
},100,function(){
keywordbox.css({display:"none",height:"auto"});
keywordbox.empty();//清空盒子内容
});
});*/
keywordbox.mouseleave(function(){//鼠标离开关键字盒子后收缩关键词盒子(取代上一个方法)
keywordbox.animate({
height:0//关键盒子收缩效果
},100,function(){
keywordbox.css({display:"none",height:"auto"});
keywordbox.empty();//清空盒子内容
});
});
var numspan=0;//用来指定选择候选词(通过方向键改变)
textb.keydown(function(event){//如果使用回车提交时,关键词盒子也可以自动收缩
if(event.which==13){
keywordbox.animate({
height:0//关键盒子收缩效果
},10,function(){
keywordbox.css({display:"none",height:"auto"});
keywordbox.empty();//清空盒子内容
});
/*$("#search_bg #button_bg form").submit(function(){
return false;//阻止提交
});*/
/*$("#search_bg #button_bg form").submit(function(e){
e.preventDefault();//阻止提交方法2
});*/
}
//按下下方向键
if(event.which==40){
if(numspan==len)
numspan=0;
for(var i=0;i<len;i++){
if(numspan==i){
keywordbox.children().eq(i).css({
"background-color":"rgba(0,0,0,0.3)"
});
}else{
keywordbox.children().eq(i).css({
"background-color":"rgba(255,255,255,0.3)"
});
}
}
textb.val(keywordbox.children().eq(numspan).html());
numspan++;
}
//按下上方向键
if(event.which==38){
numspan--;
if(numspan==len)
numspan=0;
for(var i=0;i<len;i++){
if(numspan==i){
keywordbox.children().eq(i).css({
"background-color":"rgba(0,0,0,0.3)"
});
}else{
keywordbox.children().eq(i).css({
"background-color":"rgba(255,255,255,0.3)"
});
}
}
textb.val(keywordbox.children().eq(numspan).html());
}
});
keywordbox.children().mouseover(function(){
numspan=$(this).index();
for(var i=0;i<len;i++){
if(numspan==i){
keywordbox.children().eq(i).css({
"background-color":"rgba(0,0,0,0.3)"
});
}else{
keywordbox.children().eq(i).css({
"background-color":"rgba(255,255,255,0.3)"
});
}
}
textb.val(keywordbox.children().eq(numspan).html());
});
}
效果如图:
- 最新评论
