天天看點

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;   

function createXMLHttpRequest(){

    if (window.ActiveXObject){   

        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){   

        xmlHttp = new XMLHttpRequest();

    }

   if(!xmlHttp)

      alert("建立 XMLHttpRequest 對象失敗!");

}

function startRequest(doUrl){

    createXMLHttpRequest(); 

    xmlHttp.onreadystatechange = handleStateChange;

    xmlHttp.open("GET", doUrl, true);

    xmlHttp.send(null);

}

function handleStateChange(){   

    if (xmlHttp.readyState == 4 ){

        if (xmlHttp.status == 200 ){

             // 一切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);

      }

    }

}

繼續閱讀