什么是跨域

http://www.abc.com:8080/scripts/jquery.js

http://  协议

www  子域名

abc.com 主域名

8080 端口号,一般端口号是80

scripts/jquery.js  请求资源

协议,子域名,主域名,端口号,有一个不同,就算不同域

不同域之间相互请求资源,就是 跨域

1.ajax处理跨越 jsonp,只适用于get请求

$.ajax({

   url:"",

  data:{},

  dataType:"jsonp",

  json:"callback",

  success:function(){}

});

2.iframe跨域

 页面中增加一个iframe元素,在需要调用get请求的时候,将iframe的src设置为get请求的url即可发起get请求的调用。

var url = "http://xxx.xxx.xxx?p1=1&p2=2";
$("#iframe").attr("src", url);//跨域,使用iframe

iframe方式强于jsonp,除了可以处理http请求,还能够跨域实现js调用。

3.script元素的src属性处理

 iframe、img、style、script等元素的src属性可以直接向不同域请求资源,jsonp正是利用script标签跨域请求资源的简单实现,所以这个和jsonp本质一样,同样需要服务端请求返回callback...形式。

var url="http://xxx.xxx.xxx?p1=1";
var script = document.createElement('script');
script.setAttribute('src', url);
document.getElementsByTagName('head')[0].appendChild(script);

4.在服务器使用get处理。

对于业务上没有硬性要求在前端处理的,可以在服务端做一次封装,再服务端发起调用,这样就可以解决跨域的问题。然后再根据请求是发出就完,还是需要获取返回值,来决定代码使用同步或者异步模式。

private static void CreateGetHttpResponse(string url, int? timeout, string userAgent, CookieCollection cookies)
        {
            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException("url");
            }
            var request = WebRequest.Create(url) as HttpWebRequest;
            request.Method = "GET";
            if (!string.IsNullOrEmpty(userAgent))
            {
                request.UserAgent = userAgent;
            }
            if (timeout.HasValue)
            {
                request.Timeout = timeout.Value;
            }
            if (cookies != null)
            {
                request.CookieContainer = new CookieContainer();
                request.CookieContainer.Add(cookies);
            }
            request.BeginGetResponse(null,null);//异步
            //return request.GetResponse() as HttpWebResponse;
        }
5.flash跨域
原文地址:https://www.cnblogs.com/xiaotaiyang/p/5495051.html