首先,JS不可以直接跨域请求JSON数据,但是JS可以跨域加载JS。
那么什么是跨域请求呢?
1、域名不同
2、域名相同,但是端口不通
以上两个请求都属于跨域请求,只有域名和端口完全一样才不是跨域。
例如:
www.taotao.com --->请求www.taobao.com 也是跨域
www.taotao.com-->请求sso.taotao.com 也是跨域
www.taotao.com:8080-->www.taotao.com:8088 也是跨域
localhost:8080-->localhost:8088 也是跨域
www.taotao.com-->www.taotao.com 不是跨域。
场景:taotao-portal-web(testportal.jsp)请求taotao-sso-web(sso_json.json、sso_js.js)
1、taotao-portal-web的 testportal.jsp,跨域请求taotao-sso-web的sso_json json数据。
testportal.jsp如下:
<script type="text/javascript">
$(function(){
$.ajax({
url:"http://localhost:8089/js/sso_json.json",
type:"get",
dataType:"json",
success:function(data){
alert("success");
}
});
})
sso_json如下:
{
"id":1
}
相当于http://localhost:8082/testportal.jsp 跨域请求 http://localhost:8089/js/sso_json.json。dateType为 json
结果报错:Failed to load http://localhost:8089/js/sso_json.json: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8082' is therefore not allowed access.
2、taotao-portal-web的 testportal.jsp,跨域请求taotao-sso-web的sso_js.js js数据。
testportal.jsp如下:
<script type="text/javascript">
$(function(){
$.ajax({
url:"http://localhost:8089/js/sso_js.js",
type:"get",
dataType:"script",
success:function(data){
alert("jschengg");
}
});
})
</script>
sso_js.js如下:
function fun(data){
alert(data);
}
相当于http://localhost:8082/testportal.jsp 跨域请求 http://localhost:8089/js/sso_js.js。dateType为 script
结果正常访问。
3、既然JS不能跨域请求JSON,那么是否能通过JS跨域请求JS来变相请求JSON?
testportal.jsp如下: dateType json改为script
<script type="text/javascript">
$(function(){
$.ajax({
url:"http://localhost:8089/js/sso_json.json",
type:"get",
dataType:"script",
success:function(data){
alert("success");
}
});
})
这次似乎请求成功了,界面弹出了success,但是浏览器的console控制台报错:
Uncaught SyntaxError: Unexpected token : 译为意外的符号
该处原因为,dataType:"script"请求的应该是JS数据,但是却意外的得到了JSON数据。
修改 sso_json,将JSON改成JS格式的数据
fun({
"id":1
})
再次请求http://localhost:8082/testportal.jsp报错,Uncaught ReferenceError: fun is not defined
提示在sso_json中的fun方法没有定义,那么在testportal.jsp顶一下 fun 方法,fun方法里面参数就是JSON数据
<script type="text/javascript">
function fun(data){
alert(data.id);
}
$(function(){
$.ajax({
url:"http://localhost:8089/js/sso_json.json",
type:"get",
dataType:"script",
success:function(data){
alert("success");
}
});
})
</script>
再次请求成功: 其中 1 为sso_json中 id的值