最近在一个项目中遇到了ajax跨域的问题,情况如下。有三个域名分别是 a.xx.com b.xx.com c.xx.com 这三个域名都会用用ajax post方式相互读取数据。文笔不好, 不写了妈蛋。自己去看
//a.html
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title></title> 6 </head> 7 <body> 8 9 <script type="text/Javascript" charset="utf-8"> 10 var Ajax = { 11 idf : "STONE", 12 frm:null, 13 ifm:null, 14 attribute:{ 15 url:null, 16 type:"post", 17 data:null, 18 success:'Ajax.defaultFunction', 19 beforeSend:null, 20 jsonp: "callbackparam" 21 }, 22 //跨域 23 init:function(){ 24 //创建iframe元素 25 this.ifm = this.createDOM("iframe",{ 26 name:"iframe"+this.idf, 27 id:"iframe"+this.idf, 28 style:"display:none", 29 width:1, 30 height:1 31 }); 32 //创建form元素 33 this.frm = this.createDOM("form",{ 34 action:this.attribute.url, 35 method:this.attribute.type, 36 id:"FORM"+this.idf, 37 name:"FORM"+this.idf, 38 target:"iframe"+this.idf 39 }); 40 document.body.appendChild(this.frm); 41 document.body.appendChild(this.ifm); 42 //回调 callbackparam 43 this.frm.appendChild( this.createDOM("input",{ 44 type:'hidden', 45 name:this.attribute.jsonp, 46 value:this.attribute.success 47 }) ); 48 //参数 input 49 this.initInput(); 50 51 this.frm.submit(); 52 //alert(1); 53 }, 54 //参数 55 initInput:function(data , inputname){ 56 57 //判断initIuput是否是第一次 58 if(typeof data != "object"){ 59 data = this.attribute.data; 60 } 61 for(i in data){ 62 var iname = inputname ? inputname + "["+i+"]" : i; 63 64 if(typeof data[i] == "object"){ 65 this.initInput(data[i], iname); 66 }else{ 67 this.frm.appendChild( this.createDOM("input",{ 68 type:'hidden', 69 name:iname, 70 value:data[i] 71 }) ); 72 } 73 } 74 75 }, 76 77 //创建DOM 78 createDOM:function(Element , data){ 79 var e = document.createElement(Element); 80 for(i in data){ 81 e.setAttribute(i,data[i]); 82 } 83 return e; 84 }, 85 //默认返回处理函数 86 defaultFunction:function(){ 87 console.log("不错!/n可以去搞基!"); 88 }, 89 //清除残留 90 del:function(){ 91 //document.body.removeAttribute(Ajax.frm); 92 //console.log(this); 93 //提交后的回调 94 }, 95 //合并对象 96 extend:function(o,n,override){ 97 for(var p in n){ 98 if(n.hasOwnPRoperty(p) && (!o.hasOwnProperty(p) || override)){ 99 o[p]=n[p];100 }101 }102 },103 call:function(option){104 //赋值105 this.extend(this.attribute , option , true);106 //提交107 108 this.init(); 109 110 this.ifm.onload = this.del;111 }112 113 }114 //使用115 //如果是跨域请记得把 document.domain 设成一样116 document.domain = "xx.com"; 117 Ajax.call({118 url:'iframe.html', 119 type:'post',120 data:{ddd:"a",a:{b:2,c:{l:0}}}121 });122 </script>123 </body>124 </html>
iframe.html
<!DOCTYPE html><html> <head> <meta charset="utf-8"> <title></title> </head> <body> <script type="text/javascript" charset="utf-8"> document.domain = "xx.com"; parent.Ajax.defaultFunction() </script> </body></html>
现在只可以在子域名下跳跳,哪位大神有兴趣可以改成无限制跨域
新闻热点
疑难解答