js跨域问题(2)
前两天碰到一个跨域问题的处理,使用jsonp可以解决。(http://www.cnblogs.com/xtechnet/p/4123210.html)
最近再整理了一下:
非CORS
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跨越
过于尖端了==,再研究
二.CORS
http://www.w3.org/wiki/CORS_Enabled#For_IIS7
Merge this into the [web.config] file at the root of your application / site:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>
If you don't have a web.config file already, or don't know what one is, just create a new file called "web.config" containing the snippet above.
跨域资源共享,Cross-Origin Resource Sharing)
跨源资源共享标准通过新增一系列 HTTP 头,让服务器能声明那些来源可以通过浏览器访问该服务器上的各类资源:CSS、图片、js脚本以及其它类资源。趋势。。
参考:
http://www.cnblogs.com/think/archive/2010/06/23/1763616.html
http://www.jb51.net/article/42472.htm
http://www.jb51.net/article/29180.htm
最新文章
- NodeJS 学习总结 01 安装配置
- MaxScale:实现MySQL读写分离与负载均衡的中间件利器
- 让input不可编辑的方法
- SQLite Version3.3.6源代码文件结构
- html5中的常用的库
- [linux]磁盘挂载
- Android 实现GIF播放(解码)
- 小草手把手教你 LabVIEW 串口仪器控制——初识VISA串口
- 使用NPOI-创建Excel
- Linux文件系统及常用命令
- 莫烦keras学习自修第三天【回归问题】
- 接口压测初识java GC
- TS-Node 体验
- BZOJ3718[PA2014]Parking——树状数组
- 随机数类Random
- 基础知识《十一》Java异常处理总结
- 首次进入页面的时候用js刷新页面
- [Lua] 尾调用消除(tail-call elimination)
- IntelliJ IDEA Java项目中添加jar包
- parseInt(";08";)或parseInt(";09";)转换返回0的解决办法