前两天碰到一个跨域问题的处理,使用jsonp可以解决。(http://www.jb51.net/article/57889.htm)
最近再整理了一下:
1.jsonp。
ajax请求,datatype为jsonp。这种形式需要请求在服务端调整为返回callback([json-object])的形式。如果服务端返回的是普通json对象。那么调试的时候,在chrome浏览器的控制台会报uncaught syntaxerror: unexpected token错误;在firefox浏览器的控制台会报syntaxerror: missing ; before statement错误。
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跨域
过于尖端了==,再研究
总结:以上5种方法就是常见的解决js跨域问题的处理方法了,最后一种比较高端,等我研究清楚了再补上吧。