/*************** prototype 同步请求 ********************/
var Transfer={}
Transfer.Base = function() {}
Transfer.Base.prototype = {
setOptions: function(options) {
if(typeof options!="object"){options={};}
this.options = {
bCache:options.bCache||false,
id:options.id||"scriptTemp",
onfailure:options.onfailure||function(){},
oncomplate:options.oncomplate||function(){}
}
}
}
var Class = {
create: function() {
return function() {
this.initialize.apply(this, arguments);
}
}
}
Object.extend = function(destination, source) {
for (var property in source) {
destination[property] = source[property];
}
return destination;
}
/**
new Transfer.Request(url,{oncomplate:'',id:''})
*/
Transfer.Request=Class.create();
Transfer.Request.prototype=Object.extend(new Transfer.Base(),{
initialize: function(url, options) {
this.setOptions(options);
this.request(url);
},
request:function(url){
this.url=url;
this.bCache=this.options.bCache;
this.id=this.options.id;
this.oncomplate=this.options.oncomplate;
this.onfailure=this.options.onfailure;
this.symbol="?";
if(this.url.indexOf("?")!="-1")this.symbol="&";
var head=document.getElementsByTagName("head")[0];
var sT = document.getElementById(this.id);
if(sT&&sT.src&&sT.src==this.url){
this.oncomplate();
return;
}
if (sT) {sT.parentNode.removeChild(sT);}
var s = document.createElement("script");
head.appendChild(s);
s.setAttribute("language", "javascript");
s.setAttribute("type", "text/javascript");
s.setAttribute("id", this.id);
s.setAttribute("src", (this.bCache && this.bCache == true) ? this.url + this.symbol + Math.random() : this.url);
var self=this;
s.onload=s.onreadystatechange=function()
{
if (typeof ActiveXObject!="undefined") {
if(s.readyState&&s.readyState=="loaded")self.oncomplate();
if(s.readyState&&s.readyState=="complete")return;
}else{
self.oncomplate();
}
}
s.onerror=function(){ //ie not work
s.parentNode.removeChild(s);
self.onfailure();
throw new Error("some error occurd,please try again later");
}
}
});
/********************************************/
调用方法:
new Transfer.Request("./decode.jsp?timestamp="+new Date().getTime()+""+parseInt(Math.random()*1000),{oncomplate:getLatlonCallback,id:'getLatlonCallback',bCache:true});
传入参数的方法:
new Transfer.Request(url,{oncomplate:function(){getAreaList(city[0]);},id:"areabycity_1",bCache:true});