Ajax與DOM實現動態加載


首先說下問題背景:想要通過異步請求一個文本文件,然后通過該文件的內容動態創建一個DOM節點添加到網頁中。

基於這個需要了解:

  1 DOM如何動態添加節點

  2 Ajax異步請求

  3 Chrome瀏覽器如何處理本地請求

  DOM如何動態添加節點

  想要動態的添加節點,就需要良好的理解DOM文檔。

  常用的幾個方法:

  getElementById()  getElementsByTagName() getAttribute() setAttribute()

  以及

  createElement() createTextNode() appendChild()

  等等。

  下面看一下創建一個DOM節點的方法過程,首先需要有一個掛載的div,這個div需要設置上一個id,這樣方便通過getElementById來獲取。

        <div id="test"></div>

        <script type="text/javascript">
             var para = document.createElement("p");//創建一個p標簽節點
             var txt  = document.createTextNode("文本內容");//創建一個文本節點,指定相關的內容
             para.appendChild(txt);//把文本節點添加到p標簽節點
             document.getElementById("test").appendChild(para);//把p標簽節點,添加到div中
        </script>

  這樣就完成了動態的創建節點。

  Ajax異步請求

  首先針對不同的瀏覽器,創建XMLHttpRequest對象,可以采取下面的方法:

            function getHTTPObject(){
                if(typeof XMLHttpRequest == "undefined"){
                    XMLHttpRequest = function(){
                        try{
                            return new ActiveXObject("Microsoft.XMLHTTP");
                        }catch(e){}
                        return false;
                    }
                }
                return new XMLHttpRequest();
            }

  這樣就可以返回瀏覽器支持的request對象了。然后創建對應的request的open send onreadystatechange方法。

  這里直接放在一個方法中:

            function getNewContent(){
                var request = getHTTPObject();
                if(request){
                    request.open("GET","test.txt",true);
                    request.onreadystatechange = function(){
                        if(request.readyState == 4){
                            //核心代碼
                        }
                    };
                    request.send(null);
                }else{
                    console.log("Browser does not support XMLHttpRequest");
                }
                console.log("Function Done!");
            }

  然后等待出發getNewContent就可以了。

  全部代碼:

<!doctype html>
<html>
    <head>
         <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
         <title>Ajax test</title>
    </head>
    <body>
        <div id="test"></div>

        <script type="text/javascript">
            function getHTTPObject(){
                if(typeof XMLHttpRequest == "undefined"){
                    XMLHttpRequest = function(){
                        try{
                            return new ActiveXObject("Microsoft.XMLHTTP");
                        }catch(e){}
                        return false;
                    }
                }
                return new XMLHttpRequest();
            }

            function getNewContent(){
                var request = getHTTPObject();
                if(request){
                    request.open("GET","test.txt",true);
                    request.onreadystatechange = function(){
                        if(request.readyState == 4){
                            console.log("Response Received!");
                            var para = document.createElement("p");
                            var txt  = document.createTextNode(request.responseText);
                            para.appendChild(txt);
                            document.getElementById("test").appendChild(para);
                        }
                    };
                    request.send(null);
                }else{
                    console.log("Browser does not support XMLHttpRequest");
                }
                console.log("Function Done!");
            }

            function addLoadEvent(func){
                var oldonload = window.onload;
                if(typeof window.onload != 'function'){
                    window.onload = func;
                }else{
                    window.onload = function(){
                        oldonload();
                        func();
                    }
                }
            }

            addLoadEvent(getNewContent);
        </script>
    </body>
</html>
View Code

  執行結果:

  Chrome處理本地Ajax異步請求

  由於Chrome不支持本地的異步請求,因此直接通過file://訪問文件就會報錯!

  報錯信息如下:

  XMLHttpRequest cannot load file:///C:/Users/Administrator/Desktop/test.txt. Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, https, chrome-extension-resource.

  Uncaught NetworkError: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'file:///C:/Users/Administrator/Desktop/test.txt'.

 

  所以在Chrome的快捷方式后面添加:--allow-file-access-from-files 即可。注意后面要添加一個空格,不然會提示錯誤!

  正確的寫法:

  "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --allow-file-access-from-files

  這樣就可以正確訪問了。

  參考:

  【1】《Javascript DOM編程藝術》

  【2】如何解決XMLHttpRequest cannot load...:http://blog.csdn.net/dandanzmc/article/details/31344267/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM