使用Ajax異步加載請求JSON數據

html

<!DOCTYPE html>
<html>
    <head lang="en">
        <meta charset="UTF-8">
        <title></title>
        <script src="addLoadEvent.js"></script>
        <script src="getHttpObject.js"></script>
        <script src="getNewContent.js"></script>
    </head>
    <body>
    </body>
</html>

demo.json

[
  {
    "name":"Lee",
    "age":28,
    "height":188
  },
  {
    "name":"Sun",
    "age":30,
    "height":190
  }
]

addLoadEvent.js

function addLoadEvent(fun){
    var oldLoad = window.onload;
    if(typeof  oldLoad != "function"){
        window.onload = fun;
    }else{
        window.onload = function(){
            oldLoad();
            fun();
        }
    }
}

getHttpObject.js

/*建立XMLHttpRequest對象的兼容方法*/
function getHttpObject(){
    if(window.XMLHttpRequest){
        return new XMLHttpRequest();
    }else if(window.ActiveXObject){
        return new ActiveXObject("Microsoft.XMLHTTP");
    }
}

getNewContent.js

function getNewContent(){
    /*建立一個新的getHttpObject對象*/
    var XHR = getHttpObject();
    if(XHR){
    XHR.onreadystatechange = function(){
    if(XHR.readyState == 4 && XHR.status == 200){
        var txt = JSON.parse(XHR.responseText);
        var result = [];
        /*動態添加DOM*/
        var body = document.getElementsByTagName("body")[0];
        var content = document.createElement("p");
        body.appendChild(content);
        /*遍歷輸出*/
        for(var i=0;i<txt.length;i++){
            result["name"] = txt[i].name;
            result["age"] = txt[i].age;
            result["height"] = txt[i].height;
            content.innerHTML += "姓名:"+result["name"]+"&nbsp;&nbsp;年齡:" + result["age"] +"&nbsp;&nbsp;身高:"+ result["height"]+"<br/>";
            }
        }
    };
    /*異步請求觸發後,腳本會繼續執行,不會等待它響應*/
    XHR.open('Get','demo.json?id='+Math.random(),true);
    XHR.send(null);
    }
}
addLoadEvent(getNewContent);

運行結果

這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章