AJAX跨域方案一:CORS
当发送ajax请求时,服务器会返回一个响应头,相当于服务器指定了可以访问该接口的白名单,通常,只对于那些公开的非隐私的数据接口,才会使用CORS
只需要在服务器端设置响应头部信息即可,*代表所有都可访问
response.setHeader("Access-Control-Allow-Origin", "*");
AJAX跨域方案二:jsonp
jsonp是json的一种使用模式,可以让网页从别的域名那里获取数据
// 当输入框中内容改变时,会触发事件
$("#searchInput").on("input", function(){
$.ajax({
// 使用百度的接口,搜索参数为输入框中的内容
url: "http://suggestion.baidu.com/su?wd="+$(this).val(),
// 使用jsonp解决跨域问题
dataType: "jsonp",
success: function(data) {
// 将上次一获取的内容清空
$(".droplist").empty();
// 遍历获取到的数据
data.s.forEach(function(item){
// 拼接到页面上
$(".droplist").append( $("<li>"+item+"</li>") )
})
},
// 因为百度接口的回调函数不为callback,是cb,所以需要格外转换一下
jsonp: "cb"
})
})
AJAX跨域方案三:服务器转发
服务器端向第三方服务器发起请求,得到数据,并返回给客户端
举例:使用接口获取猫眼电影
-
url的地址前面使用本地服务器地址http://localhost:9090/proxy,其中proxy为代理服务器,后面拼接的地址为猫眼域名之后的地址/ajax/movieOnInfoList
-
猫眼地址:https://m.maoyan.com/ajax/movieOnInfoList
-
因为传输过来的数据时string类型的,所以需要转换成json类型
dataType: "json"
-
data.movieList为取出来的电影数据,然后遍历每一条,因为每条数据中的图片地址不可直接访问,所以需要处理
-
然后使用template方法将数据封装到页面模板中,那个页面模板的id位movie-temp,而模板中使用的变量为list,所以可以传入一个对象属性,然后属性名为list,属性值为取出的数据
-
最后将数据创建到页面上
function init(){
$.ajax({
url: "http://localhost:9090/proxy/ajax/movieOnInfoList",
dataType: "json",
success: function(data) {
data.movieList.forEach(function(item){
item.img = item.img.replace('w.h/','');
})
console.log(data.movieList);
var htmlstr = template("movie-temp", {
list: data.movieList
})
$("#movies-wrapper").html(htmlstr);
}
});
}
页面模板
<script id="movie-temp" type="text/html">
<% for(var i=0; i<list.length; i++) { %>
<div class="col-lg-3 col-md-3 col-sm-6 col-xs-12">
<div class="panel panel-default">
<div class="panel-body text-center">
<img movieid=<%=list[i].id%> src="<%=list[i].img %>" class="img-thumbnail">
</div>
<div class="panel-footer"> 《<%=list[i].nm%>》 </div>
</div>
</div>
<% } %>
</script>