Javascript跨域请求的几种解决方法

什么情况下才会出现跨域?
假设域名是:http://www.example.com.cn/
如果所请求的域名跟这个域名不致,这种情况就是跨域,由于跨域存在漏洞,所以一般来说正常的跨域请求方式是请求不到的。
 
解决方式:
一、window.name
1、 服务器返回
 

<script>window.name='{“id”:”3″, “name”:”leisure”}';</script>

2、定义一个iframe,添加onload事件 <iframe id=”iframe1″ onload=”iLoad”><iframe>
<script type=”text/javascript”>
var load = false;
function iLoad() {
if(load == false) {
// 同域处理,请求后会再次重新加载iframe
document.getElementById(‘iframe1′).contentWindow.location = ‘/';
load = true;
} else {
// 获取window.name的内容,注意必须进行同域处理后方可访问!
var data = document.getElementById(‘iframe1′).contentWindow.name;
alert(data); // {“id”:”3″, “name”:”leisure”}
load = false;
}
}
</script>
3、定义一个form,设置form的target为iframe的id,然后提交form
<form action=”url” method=”POST” target=”iframe1″>
<button type=”submit” value=”submit” />
</form>
 
 
二、JSONP
服务器返回 callback({“id”: “3”, “name”: “leisure”});
<script type=”text/javascript”>
function callback(data) {
alert(data);
}
</script>
<script type=”text/javascript” src=”http://www.example.com.cn/product.jsp?id=5&jsonp=callback”></script>
 
三、jQuery.getJSON
服务器返回 json格式数据 test({“id”: “3”, “name”: “leisure”}); test函数名为callback参数中定义
$.getJSON(url + “?callback=?”, data, function(data) {
 
}
注意callback=?这个参数必须带上,jquery会自动生成一个函数名替换这个问号!jQuery.getJSON实际上是用了JSONP方式实现。
 
四、flash跨域
服务器添加crossdomain.xml
http://www.example.com.cn/crossdomain.xml
<?xml version=”1.0″?>
<cross-domain-policy>
<allow-access-from domain=”*.another.com.cn” />
</cross-domain-policy>
 
转载地址:http://www.wufangbo.com/js-kua-yu-ji-zhong/
原文地址:https://www.cnblogs.com/smght/p/4977237.html