[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);
};
})();