<!--
JSONP由回调函数和数据组成
通过查询字符串指定当响应到来时在页面中调用的函数
可以直接访问响应文本,实现双向通信,不过无法保证响应内容的安全性
-->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>跨域--jsonp--百度搜索</title>
<style type="text/css">
html,body,div,input,ul,li,a{
margin: 0;
padding: 0;
}
#baiduSearch{
position: absolute;
top: 10px;
}
#baiduSearch{
left: 100px;
}
#baiduSearch input{
width: 300px;
height: 30px;
padding: 5px;
border: 1px solid #F90;
font-size: 16px;
}
#baiduSearch ul{
display: none;
width: 310px;
border: 1px solid #F90;
}
#baiduSearch li{
list-style: none;
}
#baiduSearch li a{
padding: 5px;
text-decoration: none;
line-height: 30px;
color: #000;
}
#baiduSearch li a:hover{
display: block;
color: #FFF;
background-color: #F90;
}
</style>
</head>
<body>
<div id="baiduSearch">
<input type="text" value="" name="q" placeholder="百度搜索">
<ul></ul>
</div>
<script type="text/javascript">
var oBaidu = document.getElementById("baiduSearch");
var baiduSearch = oBaidu.getElementsByTagName("input")[0];
var baiduList = oBaidu.getElementsByTagName("ul")[0];
function baiduSug(data) {
var html = "";
if (data.s.length) {
baiduList.style.display = "block";
for (var i=0; i<data.s.length; i++) {
html += "<li><a target='_blank' href='https://www.baidu.com/s?wd=" + data.s[i] + "'>"+ data.s[i]+"</a></li>";
};
baiduList.innerHTML = html;
} else {
baiduList.style.display = "none";
};
}
baiduSearch.onkeyup = function () {
if (this.value != "") {
var oScript = document.createElement("script");
oScript.src = "http://suggestion.baidu.com/su?cb=baiduSug&wd="+this.value;
if (document.body) {
document.body.appendChild(oScript);
} else {
document.documentElement.appendChild(oScript);
};
} else {
baiduList.style.display = "none";
};
}
</script>
</body>
</html>
</body>
</html>