跨域请求之JSONP
跨域恳求的方法有很多种, 1,iframe 2,document.domain 3,window.name 4,script 5,XDomainRequest (IE8+) 6,XMLHTTPRequest (Firefox3.5+) 7,postMessage (HTML5) 8,后台代理 ... 它们有各自的优缺点,回来的数据格局也各不同,应根据需要慎重挑选。比方iframe回来html片段就对比适合,费老劲用它回来JSON就因小失大了。这篇开端我将打造一个有用的跨域恳求东西Sjax。运用script恳求的最大缺点,挑战是过错处理。比方404过错,它不象XMLHTTPRequest能精确的回来状况码404。我把这个放在最终一篇。 本系列首要描绘以上列举的方法4,即通过script回来JSON格局数据数据。这种方法如今称为JSONP。JSON是目前前后台交流运用最盛行,也最广泛的格局之一。相对于前期的AJAX回来XML(AJAX中的X即是XML),JSON显得更轻量级,没有剩余的Tag符号,解析也是原生的。XML回来到前端后先转成文档,通过DOM API一层层的解析。解析DOM是开支对比大的,尤其在前期的IE版别中(IE6/7/8),core js与dom交流的价值是很大的。 JSONP的实现思路很简单 1,前端创立script符号,设置src,添加到head中(你可以往body中添加)。 2,后台回来一个js变量jsonp,这个jsonp即是恳求后的JSON数据。 3,回调完成后删去script符号(还有一些整理作业如防止有些浏览器内存泄露等)。 接口 Sjax.load( url,// 跨过恳求的URL success,// 回调函数,有必要界说一个形参,用于接纳后台回来的全局变量jsonp (约好后台回来如jsonp = {...}结构) timestamp,// 传true会加一个时间戳,防止缓存,默许不加 ); <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>sjax_0.1.js by snandy</title> <script src="/js/sjax_0.1.js"></script> </head> <body> <p id="p1" style="background:gold;"></p> <input type="button" value="Get Name" onclick="clk()"/> <script type="text/javascript"> function clk(){ Sjax.load( 'http://lf.yunnanw.cn/', 'http://www.lcsyt.com/',sans-serif;font-size:14px;line-height:21px;white-space:normal;margin-top:0px;margin-bottom:0px;"> 'http://www.minnan888.net/',sans-serif;font-size:14px;line-height:21px;white-space:normal;margin-top:0px;margin-bottom:0px;"> 'http://www.vipfuxin.com/',sans-serif;font-size:14px;line-height:21px;white-space:normal;margin-top:0px;margin-bottom:0px;"> 'http://www.qclchina.com/',sans-serif;font-size:14px;line-height:21px;white-space:normal;margin-top:0px;margin-bottom:0px;"> 'http://www.tongxinglong.com/',sans-serif;font-size:14px;line-height:21px;white-space:normal;margin-top:0px;margin-bottom:0px;"> 'http://www.jinanwuliangye.com/',sans-serif;font-size:14px;line-height:21px;white-space:normal;margin-top:0px;margin-bottom:0px;"> '',sans-serif;font-size:14px;line-height:21px;white-space:normal;margin-top:0px;margin-bottom:0px;"> function(){ document.getElementById('p1').innerHTML = 'Hi,' + jsonp.name; } ); } </script> </body> </html> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |