Mozilla Firefox與IE瀏覽器中用AJAX處理XML文件的通用代碼

//
//加載XML文件
//


var xmlDoc;
 function loadXML(xmlfile){
    //load xml file
    // code for IE
    if (window.ActiveXObject)
    {
        xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async=false;
        xmlDoc.load(xmlfile);
    }
    // code for Mozilla, Firefox, Opera, etc.
    else if (document.implementation && document.implementation.createDocument)
    {
        xmlDoc=document.implementation.createDocument("","",null);
        xmlDoc.load(xmlfile);   
    }
    else
    {
        alert('Your browser cannot handle this script');
    }
}

//
//下載通用代碼
//

var xmlHttp;    /*XMLHttpRequest對象 */
function createXMLHttpRequest(){
    if (window.ActiveXObject){    /*在IE下初始化XMLHttpRequest對象 */
        try{
              //新版本的 Internet Explorer
              xmlHttp= new ActiveXObject("Msxml2.XMLHTTP");
        }catch (otherMicrosoft){
              try {
                   //較老版本的 Internet Explorer
                  xmlHttp= new ActiveXObject("Microsoft.XMLHTTP");
              } catch (failed){
                   // 還是失敗,那麼就認爲創建失敗……
                   xmlHttp= false;
               }            
    }  else if(window.XMLHttpRequest){    /*在Firefox下初始化XMLHttpRequest對象 */
        xmlHttp = new XMLHttpRequest();
    }
   if(!xmlHttp)
      alert("創建 XMLHttpRequest 對象失敗!");
}
 
function startRequest(doUrl){
    createXMLHttpRequest(); 
    xmlHttp.onreadystatechange = handleStateChange; /* 設置回調函數爲handleStateChange. */
    xmlHttp.open("GET", doUrl, true); /*通過get方法來請求目標
doUrl並且設置爲異步完成請求*/
    xmlHttp.send(null);
}
 
function handleStateChange(){    /*XMLHttpRequest對象內部狀態每次有變化時候都會調用 handleStateChange 函數。*/
    if (xmlHttp.readyState == 4 ){ /*請求完成*/
        if (xmlHttp.status == 200 ){ /*服務器的HTTP狀態爲200,既OK */
             // 一切OK,調用處理過程
             //    DoMyXML();
         }else if(XMLHttp.status == 404){
             //文件不存在
             alert("Requested URL is not found.");
        }else if(XMLHttp.status == 403){
            //沒有權限
            alert("Access denied.");
       }else
          alert("status is " + XMLHttp.status);
      }
    }
}
 
發佈了20 篇原創文章 · 獲贊 1 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章