Ajax 跨域问题的解决方案

[color=red]注:本文转自http://pkzhuclover.iteye.com/admin/blogs/836772[/color]

作者未对原理进行太多的说明,需要的时候自己要去读代码,我使用后会把原理补充上。

(function(){
var id = 1,
queueList = {};

function apply(o,c){
if(o){
for(var k in c){
o[k] = c[k];
}
}
return o;
}

/**
*使用方式
*scriptRequest({
* url:"http://xxx.xxx.xxx",
* callback:function(me,data){
* //具体操作方法,data为服务器返回数据.
* }
*})
*/
function ScriptRequest(config){
var me = this;
apply(me,config);
me.cb = "ScriptRequestCallback_" + id;
me.scriptID = "ScriptRequestID_" + (id++);
me.head = document.getElementsByTagName("head")[0];
me.request();
}

apply(ScriptRequest.prototype,{
/**
*请求地址.
*/
//url:""
/**
*回调作用域.
*/
//scope:null,
/**
*@cfg {String}:队列ID,相同的队列ID一次请求未完成时再次请求会自动取消同队列中的上次请求.
*/
//queue:null,
/**
*@cfg {Number}:超时时间,一次请求的最大请求时间.
*/
timeout:30000,
/**
*@cfg {Boolean}:自动取消,在有队列的情况下是否自动取消上次请求.
*/
autoCancel:true,
/**
*@cfg getter {Boolean}:是否处于请求状态.
*/
loading:false,
/**
*@cfg {String}:后台接收回调方法名的参数名称.
*以java为例如:
*String callback = request.getParameter("callback");
*out.println(callback + "("+ "'输出一串字符串'" +")").
*/
callbackName:"callback",

initUrl:function(){
var me = this,
code = "?";
if(me.url.indexOf("?") != -1){
code = "&";
}
me.url += code + me.callbackName + "=" +me.cb;
},

request:function(){
var me = this;
me.transactQueue();
me.initUrl();
me.bindListeners();
var script = document.createElement("script");
script.setAttribute("src", me.url);
script.setAttribute("type", "text/javascript");
script.setAttribute("id", this.scriptID);
me.script = script;
me.head.appendChild(script);
me.loading = true;
},

bindListeners:function(){
var me = this;
window[me.cb] = function(data){
me.release();
me.callback && me.callback.call(me.scope || me,me,data);
}
me.timeoutThread = setTimeout(function(){
me.cancel();
},this.timeout);
},

transactQueue:function(){
var me = this,
queue=me.queue;
if(queue){
var request = queueList[queue];
request && me.autoCancel && request.cancel();
queueList[queue] = me;
}
},

cancel:function(){
this.release();
},

release:function(){
var me = this;
if(me.loading){
me.loading = false;
clearTimeout(me.timeoutThread);
window[me.cb] = undefined;
try{
delete window[me.cb];
}catch(e){}
me.script && me.head.removeChild(me.script);
}
}
});

this.scriptRequest = function(config){
return new ScriptRequest(config);
};
})();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值