看到JSONP我们会很自然的想到JSON,但它们却有很大的不同,JSON是一种轻量级的数据交换格式,而JSONP可以说是一种非官方的数据交互协议。
JSONP(JSON with padding),利用JSONP可以从别的域名下获取数据,即跨域获取数据。由于同源策略不允许XMLHttpRequest进行跨域请求,所以通过AJAX无法获取其他域名下的数据。但我们知道
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<script>
function fn(data){ //定义一个全局函数,用来对其他域名下的数据进行分析我们可以发现,这块和请求成功后AJAX对数据进行操作很像
var oList=document.getElementById('list');
var html='';
if(data.s.length){
for(var i=0; i<data.s.length;i++){
oList.style.display='block';
html+='<li><a target="_blank" href="https://www.baidu.com/s?wd='+data.s[i]+'">'+data.s[i]+'</a></li>';
}
oList.innerHTML=html;
}else{
oList.style.display='none';
}
}
window.onload=function(){
var oSearch=document.getElementById('search');
var oList=document.getElementById('list');
var oScript='';
oSearch.onkeyup=function(){
if(this.value!=''){
if(oScript){ //为了消除重复创建的<script>
document.body.removeChild(oScript);
}
oScript=document.createElement('script'); //动态创建<script>实现异步加载其他域名下的数据地址
oScript.src='https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd='+encodeURI(this.value)+'&cb=fn' //我用的是百度下的数据地址做的例子,cb=fn请求后的数据放进fn这个回调函数里。
document.body.appendChild(oScript);
}else{
oList.style.display='none';
}
}
}
</script>
<style>
*{ margin:0; padding:0;}
#search{ width:300px; height:30px; border:1px solid #f00; padding:5px; margin-left:30px;}
#list{ border:1px solid #f00; width:310px; margin-left:30px; display:none;}
#list li{ list-style: none;}
#list li a{ display: block; height:30px; line-height: 30px; text-decoration: none; color:#000;}
#list li a:hover{ background-color:#f00; color:#fff;}
</style>
<body>
<input type="text" placeholder="请输入你要查询的内容" id="search">
<ul id="list"></ul>
</body>
</html>