javascript 不用ajax 用 iframe 子域名下做到ajax post数据

时间:2022-03-30 08:37:15

最近在一个项目中遇到了ajax跨域的问题,情况如下。有三个域名分别是 a.xx.com b.xx.com c.xx.com 这三个域名都会用用ajax post方式相互读取数据。文笔不好, 不写了妈蛋。自己去看

//a.html

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body> <script type="text/javascript" charset="utf-8">
var Ajax = {
idf : "STONE",
frm:null,
ifm:null,
attribute:{
url:null,
type:"post",
data:null,
success:'Ajax.defaultFunction',
beforeSend:null,
jsonp: "callbackparam"
},
//跨域
init:function(){
//创建iframe元素
this.ifm = this.createDOM("iframe",{
name:"iframe"+this.idf,
id:"iframe"+this.idf,
style:"display:none",
width:1,
height:1
});
//创建form元素
this.frm = this.createDOM("form",{
action:this.attribute.url,
method:this.attribute.type,
id:"FORM"+this.idf,
name:"FORM"+this.idf,
target:"iframe"+this.idf
});
document.body.appendChild(this.frm);
document.body.appendChild(this.ifm);
//回调 callbackparam
this.frm.appendChild( this.createDOM("input",{
type:'hidden',
name:this.attribute.jsonp,
value:this.attribute.success
}) );
//参数 input
this.initInput(); this.frm.submit();
//alert(1);
},
//参数
initInput:function(data , inputname){ //判断initIuput是否是第一次
if(typeof data != "object"){
data = this.attribute.data;
}
for(i in data){
var iname = inputname ? inputname + "["+i+"]" : i; if(typeof data[i] == "object"){
this.initInput(data[i], iname);
}else{
this.frm.appendChild( this.createDOM("input",{
type:'hidden',
name:iname,
value:data[i]
}) );
}
} }, //创建DOM
createDOM:function(Element , data){
var e = document.createElement(Element);
for(i in data){
e.setAttribute(i,data[i]);
}
return e;
},
//默认返回处理函数
defaultFunction:function(){
console.log("不错!\n可以去搞基!");
},
//清除残留
del:function(){
//document.body.removeAttribute(Ajax.frm);
//console.log(this);
//提交后的回调
},
//合并对象
extend:function(o,n,override){
for(var p in n){
if(n.hasOwnProperty(p) && (!o.hasOwnProperty(p) || override)){
o[p]=n[p];
}
}
},
call:function(option){
//赋值
this.extend(this.attribute , option , true);
//提交 this.init(); this.ifm.onload = this.del;
} }
//使用
//如果是跨域请记得把 document.domain 设成一样
document.domain = "xx.com";
Ajax.call({
url:'iframe.html',
type:'post',
data:{ddd:"a",a:{b:2,c:{l:0}}}
});
</script>
</body>
</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>

现在只可以在子域名下跳跳,哪位大神有兴趣可以改成无限制跨域