JSONP跨域的使用流程
1.先声明一个函数,这个函数有一个形参。这个形参会拿到想要下载的数据,可以使用这个形参做后续的数据处理
2.在需要下载数据时,动态创建script标签,将标签的src设置成下载数据的链接
3.当script插入到页面时,就会调用已封装好的函数,将需要的数据传过来
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>百度搜索框</title>
<style>
body{
text-decoration: none;
}
#div1 {
width: 312px;
height: 200px;
position: absolute;
left: 50%;
top: 50%;
margin-left: -100px;
margin-top: -200px;
}
#q{
height: 30px;
width: 235px;
}
#ul1{
text-decoration: none;
border: 1px black solid;
display: none;
margin-top: 0px;
width: 200px;
}
#ul1 li{
list-style: none;
margin-left: -40px;
}
#ul1 li a{
line-height: 30px;
padding: 5px;
text-decoration: none;
color: black;
display: block;
}
#ul1 li a:hover {
background-color: antiquewhite;
color: white;
}
</style>
<script>
function download(data){
var oUl = document.getElementById("ul1");
var arr = data.s;
oUl.innerHTML = "";
oUl.style.display = "block";
for(var i=0;i<arr.length;i++){
var newli = document.createElement("li");
var oA = document.createElement("a");
oA.innerHTML = arr[i];
oA.href = 'http://suggestion.baidu.com/su?wd='+arr[i];
oA.target = '_blank';
newli.appendChild(oA);
oUl.appendChild(newli);
}
}
</script>
<script>
window.onload = function(){
var oQ = document.getElementById("q");
var oUl = document.getElementById("ul1");
oQ.onkeyup = function(){
if(this.value != ''){
var oScript = document.createElement("script");
oScript.src = ` http://suggestion.baidu.com/su?wd=${this.value}&cb=download`;
document.body.appendChild(oScript);
}else{
oUl.style.display = "none";
}
}
}
</script>
</head>
<body>
<div id="div1">
<input type="text" id="q">
<ul id="ul1">
</ul>
</div>
</body>
</html>