2008/11/15

網頁也能動態載入 Javascript 嗎--續

上一篇網頁也能動態載入 Javascript 嗎?雖然也算動態載入,但是它無法等到正式取得之後(或是失敗)再處理,因此會有已經下命令取得外部檔,卻還沒載入完成。這是標準的 Ajax 的問題,就用 Ajax 的方式來解決。底下是另一個 mtm.js 及 net.js, 我本來的設計就是物件化的,內容如下,至於範例另外再寫一篇:


// mtm.js
function MTM()
{
this.import = function(path) {
var i, base="";
var src = 'mtm.js';
var scripts = document.getElementsByTagName("script");
var hadExisted = false;
path = path.replace(/\./g, "/") + '.js';
for (i=0; i<scripts.length; i++) {
if (scripts[i].src.match(src)) {
base = scripts[i].src.replace(src, "");
}
if (scripts[i].src.match(path)) {
hadExisted = true;
}
}
if (!hadExisted) {
document.write("<" + "script src=\"" + base + path + "\"></" + "script>");
}
}
this.insertJS = function(js) {
var scripts = document.getElementsByTagName("script");
var scr = document.createElement("script");
scr.innerHTML = js;
document.body.appendChild(scr);
}
}
var mtm = new MTM();


// net.js
var net=new Object();

net.READY_STATE_UNINITIALIZED=0;
net.READY_STATE_LOADING=1;
net.READY_STATE_LOADED=2;
net.READY_STATE_INTERACTIVE=3;
net.READY_STATE_COMPLETE=4;


/*--- content loader object for cross-browser requests ---*/
net.ContentLoader=function(url,onload,onerror,method,id,params,contentType){
this.req=null;
this.onload=onload;
this.id = id;
this.onerror=(onerror) ? onerror : this.defaultError;
this.loadXMLDoc(url,method,params,contentType);
}

net.ContentLoader.prototype.loadXMLDoc=function(url,method,params,contentType){
if (!method){
method="GET";
}
if (!contentType && method=="POST"){
contentType='application/x-www-form-urlencoded';
}
if (window.XMLHttpRequest){
this.req=new XMLHttpRequest();
} else if (window.ActiveXObject){
this.req=new ActiveXObject("Microsoft.XMLHTTP");
}
if (this.req){
try{
var loader=this;
this.req.onreadystatechange=function(){
net.ContentLoader.onReadyState.call(loader);
}
this.req.open(method,url,true);
if (contentType){
this.req.setRequestHeader('Content-Type', contentType);
}
this.req.send(params);
}catch (err){
this.onerror.call(this);
}
}
}


net.ContentLoader.onReadyState=function(){
var req=this.req;
var ready=req.readyState;
if (ready==net.READY_STATE_COMPLETE){
var httpStatus=req.status;
if (httpStatus==200 || httpStatus==0){
this.onload.call(this);
}else{
this.onerror.call(this);
}
}
}

net.ContentLoader.prototype.defaultError=function(){
alert("error fetching data!"
+"\n\nreadyState:"+this.req.readyState
+"\nstatus: "+this.req.status
+"\nheaders: "+this.req.getAllResponseHeaders());
}

0 意見: