1 /** 2 * @fileOverview ajax xhr transport class , route subdomain , xdr 3 * @author yiminghe@gmail.com 4 */ 5 KISSY.add("ajax/XhrTransport", function (S, io, XhrTransportBase, SubDomainTransport, XdrFlashTransport, undefined) { 6 7 var rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/, 8 win = S.Env.host, 9 _XDomainRequest = win['XDomainRequest'], 10 detectXhr = XhrTransportBase.nativeXhr(); 11 12 if (detectXhr) { 13 14 // slice last two pars 15 // xx.taobao.com => taobao.com 16 function getMainDomain(host) { 17 var t = host.split('.'); 18 if (t.length < 2) { 19 return t.join("."); 20 } else { 21 return t.reverse().slice(0, 2).reverse().join('.'); 22 } 23 } 24 25 26 function XhrTransport(xhrObj) { 27 var c = xhrObj.config, 28 xdrCfg = c['xdr'] || {}; 29 30 if (c.crossDomain) { 31 32 var parts = c.url.match(rurl); 33 34 // 跨子域 35 if (getMainDomain(location.hostname) == getMainDomain(parts[2])) { 36 return new SubDomainTransport(xhrObj); 37 } 38 39 /** 40 * ie>7 强制使用 flash xdr 41 * 使用 withCredentials 检测是否支持 CORS 42 * http://hacks.mozilla.org/2009/07/cross-site-xmlhttprequest-with-cors/ 43 */ 44 if (!("withCredentials" in detectXhr) && 45 (String(xdrCfg.use) === "flash" || !_XDomainRequest)) { 46 return new XdrFlashTransport(xhrObj); 47 } 48 } 49 50 this.xhrObj = xhrObj; 51 this.nativeXhr = XhrTransportBase.nativeXhr(c.crossDomain); 52 return undefined; 53 } 54 55 S.augment(XhrTransport, XhrTransportBase.proto, { 56 57 send:function () { 58 this.sendInternal(); 59 } 60 61 }); 62 63 io.setupTransport("*", XhrTransport); 64 } 65 66 return io; 67 }, { 68 requires:["./base", './XhrTransportBase', './SubDomainTransport', "./XdrFlashTransport"] 69 }); 70 71 /** 72 * 借鉴 jquery,优化使用原型替代闭包 73 * CORS : http://www.nczonline.net/blog/2010/05/25/cross-domain-ajax-with-cross-origin-resource-sharing/ 74 **/