jsonp跨域
跨域问题
什么情况下会发生跨域:
当本机请求服务器上数据的时候:会发生跨域;
当本地服务器请求其他服务器数据的时候回发生跨域;
跨域怎么处理那?

1.为什么有跨域
同源策略:基于浏览器的安全考虑,浏览器各个厂商之间出现了一个约定,这个约定叫做同源策略。这个约定的主要内容就是,域和域之间数据不共通。
所谓同源是指:协议、域名、端口相同
2.跨域的用途

当网站发展壮大到一定地步的时候,会建立很多的节点,各个节点的IP是不同的,所以跨域问题就会出现。
当测试阶段数据和本机的IP不通用的时候,那么跨域问题也会发生。
3.为什么要跨域。
因为要获得其他域中的数据;
4.前端的跨域方法
JSONP:就是利用浏览器对html标签(如:a,img,link,script等)没有做跨域请求限制的情况,使用script加载跨域接口的url。
JSONP是伟大程序员与安全策略的斗争中发明的;

JSONP就是在URL中调用function;
jsonp的封装:function jsonp(url,success,data){ data = data || {};
var str = ""; for(var i in data){ str += `${i}=${data[i]}&`; } var d = new Date();
d.setDate(d.getDate()+3);
var script = document.createElement("script"); script.src = url + "?" + str +"__wzqT=" + d; document.body.appendChild(script); window[data[data.columnName]] = function(res){ success(res); } }
这里用百度的接口做的demo,在服务器下运行:
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title></title>
<style>
*{
margin:0;
padding: 0;
}
#search{
width: 600px;
margin:0 auto;
margin-top: 100px;
position: relative;
}
#search input{
width: 480px;
height: 100%;
border: 1px solid #b6b6b6;
height: 20px;
padding: 9px 7px;
font: 16px arial;
border: 1px solid #b8b8b8;
border-bottom: 1px solid #ccc;
border-right: 0;
vertical-align: top;
outline: none;
box-shadow: none;
-webkit-appearance: textfield;
background-color: white;
-webkit-rtl-ordering: logical;
user-select: text;
}
#search button{
cursor: pointer;
box-sizing: border-box;
width: 97px;
height: 40px;
line-height: 38px;
padding: 0;
border: 0;
background: none;
background-color: #38f;
font-size: 16px;
color: white;
box-shadow: none;
font-weight: normal;
margin-left: -20px;
}
.result{
position: absolute;
padding: 9px 7px;
background: #ddd;
}
.search-res{
position: absolute;
top: 100%;
left: 0;
width: 480px;
border: 1px solid #b6b6b6;
border-top: none;
}
.search-res li{
list-style-type: none;
line-height: 20px;
padding: 2px 5px;
border-bottom: 1px solid #b6b6b6;
}
</style>
</head>
<body>
<div id="search">
<input type="text">
<ul class="search-res">
</ul>
</div>
</body>
<script src="jsonp.js"> //这里的jsonp.js就是封装的jsonp
</script>
<script>
class Search{
constructor(){
// 1获取元素,url
this.txt = document.querySelector("#search input");
this.ul = document.querySelector(".search-res");
this.url = "https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su";
this.events();
}
events(){
// 2绑定事件
var that = this;
this.txt.addEventListener("input",function(){
that.value = this.value;
that.load();
})
}
load(){
// 3引入jsonp
var that = this;
jsonp(this.url,function(res){
that.res = res.s;
that.display();
},{
columnName:"cb",
cb:"baidu",
wd:this.value,
})
}
display(){
// 4显示出来
var str = "";
for(var i = 0;i < this.res.length;i++){
str += `<li>${this.res[i]}</li>`;
}
this.ul.innerHTML = str;
}
}
new Search();
</script>
</html>
使用接口时,主要在于接口文档。
接口列表
浙公网安备 33010602011771号