百度搜索功能,以及script标签跨域
JSONP : JSON with Padding
1.script标签
2.用script标签加载资源是没有跨域问题的 在资源加载进来之前定义好一个函数,这个函数接收一个参数(数据), 函数里面利用这个参数做一些事情 然后需要的时候通过script标签加载对应远程文件资源,
当远程的文件资源被加载进来的时候, 就会去执行我们前面定义好的函数,并且把数据当作这个函数的参数传入进去1.先创建一个 script 标签 因为 script 没有跨域问题 2.然后把地址引入到src 里面 3.把 script 添加到 body 里面去 4.在外面声明一个回调函数把功能性代码放在回调函数里面 并在 src里面 cb 去跟回调函数对接
效果图 (代码如下)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<style type="text/css">
*{margin: 0;padding: 0;}
.box{width:654px;height: 45px;display: flex;margin: 50px auto;border: 2px solid #ccc;border-radius: 12px;overflow: hidden;}
.box>input{flex: 5;border: none;outline: none;text-indent: 1em;}
.box>button{flex: 1;border: none;outline: none;}
.box>button>a{width: 100%;display: block;line-height: 45px;text-decoration:none;color: #000;background-color: #e4e4e5;}
.box>button>a:hover{background-color: #cdcdce;}
.oUl{width:654px;height: 45px;margin: 0 auto;}
.oUl>li{line-height: 26px;list-style: none;}
.oUl>li>a{text-decoration: none;color: #000000;}
.oUl>li>a:hover{color: blue;}
</style>
<body>
<div class="box">
<input type="text" id="text" value="" /> <!-- 搜索框 -->
<button><a href="javascript:;" >百度一下</a></button> <!-- 搜索按钮 -->
</div>
<ul class="oUl"> <!-- 搜索展示 -->
</ul>
</body>
<script type="text/javascript">
var oUl=document.getElementsByClassName('oUl')[0];
var oLi="";
window.οnlοad=()=>{ //页面加载完成之后
text.οnkeyup=function(){ //input输入框键盘抬起事件
if(text.value!=""){
var oScript=document.createElement("script")
oScript.src="http://suggestion.baidu.com/su?wd="+this.value+"&cb=fn"
document.body.appendChild(oScript)
}else{
oUl.style.display="none"
oLi=""
}
}
}
function fn(data){
oLi=""
if(data.s.length){
oUl.style.display = 'block';
for(i=0;i<data.s.length;i++){
oLi+= '<li><a target="_blank" href="http://www.baidu.com/s?wd='+data.s[i]+'">'+ data.s[i] +'</a></li>'
}
oUl.innerHTML=oLi
}else{
oUl.style.display="none"
}
}
</script>
</html>