参考自:https://www.cnblogs.com/dowinning/archive/2012/04/19/json-jsonp-jquery.html (写的很好)
跨域的情况
跨域就是跨域名,跨端口,跨协议
直接在ajax中发起跨域的请求是获取不到相应的内容的
访问不了的案例(java)
1.在本地搭建两个tomcat端口不同的项目,我这里是8099和8098端口
2.编写controller以供测试
@RequestMapping(value="/list", produces ="application/text;charset=utf-8")
@ResponseBody
public String list(){
return "我是8098端口返回的数据";
}
3.在页面中通过ajax发起跨域和不跨域的请求进行对比
不跨域:
<a class="test1" href="#">我是测试跨域的(请求http://localhost:8098/list) 不跨域</a><br>
$(function(){
$(".test1").click(function(){
$.get('http://localhost:8098/list',function(data){
$(".p1").text(data);
});
});
});
可以得到结果:
跨域
<a class="test2" href="#">我是测试跨域的(请求http://localhost:8099/list) 跨域</a><br>
$(function(){
$(".test2").click(function(){
$.get('http://localhost:8099/list',function(data){
$(".p2").text(data);
});
});
});
是获取不到数据的,出现了跨域
Jsonp跨域请求
简单实现:
在远程编写remote.js文件,本地跨域去访问
localHandler({"result":"我是远程js带来的数据"});
本地只需要写出来资源的位置就可以跨域访问:
<script type="text/javascript" src="http://localhost:8099/js/remote.js"></script>
数据的显示:
remote.js文件,修改为数据
localHandler({"result":"我是远程js带来的数据"});
本地调用
<script type="text/javascript">
var localHandler = function(data){
alert('我是本地函数,可以被跨域的remote.js文件调用,远程js带来的数据是:' + data.result);
};
</script>
<script type="text/javascript" src="http://localhost:8099/js/remote.js"></script>
Jquery实现Jsonp跨域请求(复制的)
后台的数据:
flightHandler({
"code": "CA1998",
"price": 1780,
"tickets": 5
});
跨域调用
<script type="text/javascript" src=jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
$.ajax({
type: "get",
async: false,
url: "http://flightQuery.com/jsonp/flightResult.aspx?code=CA1998",
dataType: "jsonp",
jsonp: "callback",//传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(一般默认为:callback)
jsonpCallback:"flightHandler",//自定义的jsonp回调函数名称,默认为jQuery自动生成的随机函数名,也可以写"?",jQuery会自动为你处理数据
success: function(json){
alert('您查询到航班信息:票价: ' + json.price + ' 元,余票: ' + json.tickets + ' 张。');
},
error: function(){
alert('fail');
}
});
});
</script>