ajax三中數據格式

歡迎訪問: www.ptcms.cn

ajax中常用的三種數據格式分別爲xml, text, json(JavaScript Object Notation)。
特地將其用例結合起來,如下:

<html><head>
<script>
var xmlHttp;
function createXMLHttpRequest(){
    if(window.ActiveXObject){
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else if(window.XMLHttpRequest){
        xmlHttp = new XMLHttpRequest();
    }
}
function xmlReq(){
    createXMLHttpRequest();
    xmlHttp.onreadystatechange = xmlhandle;
    xmlHttp.open("GET", "data.xml", true);
    xmlHttp.send(null);    //發送請求
}
function xmlhandle(){
    if(xmlHttp.readyState == 4){        
        if (xmlHttp.status == 200 || xmlHttp.status == 0){
         var xmlDOM = xmlHttp.responseXML;// 取得XML的DOM對象
         var root = xmlDOM.documentElement;
         var info = root.getElementsByTagName('info');// 取得<info>結果
         alert("XML's value: " + info[0].firstChild.data);
        }
    }
}

function txtReq(){
    createXMLHttpRequest();
    xmlHttp.onreadystatechange = txthandle;
    xmlHttp.open("GET", "data.txt", true);
    xmlHttp.send(null);    //發送請求
}
function txthandle(){
    if(xmlHttp.readyState == 4){        
        if (xmlHttp.status == 200 || xmlHttp.status == 0){
         alert("Text's value: " + xmlHttp.responseText);
        }
    }
}

function jsonReq(){
    createXMLHttpRequest();
    xmlHttp.onreadystatechange = jsonhandle;
    xmlHttp.open("GET", "data.txt", true);
    xmlHttp.send(null);    //發送請求
}
function jsonhandle(){
    if(xmlHttp.readyState == 4){        
        if (xmlHttp.status == 200 || xmlHttp.status == 0){
            var resp = xmlHttp.responseText;// 構造返回JSON對象的方法
            var func = new Function("return "+resp);
            var json = func();// 得到JSON對象
            alert("JSON's value: " + json.info + "(" + json.version + "v)");
        }
    }
}
</script>
<title>Ajax Hello World</title>
</head>
<body>
<input type="button" value="XML" onclick="xmlReq();" />
<input type="button" value="Text" onclick="txtReq();" />
<input type="button" value="JSON" onclick="jsonReq();" />
</body>
</html>


其中用到的data.txt:

{
info: "hello weixq!",
version: "2.0"
}

data.xml:

<?xml version="1.0" encoding="GB2312" ?>
<root>
    <info>hello world!</info>
</root>

發佈了36 篇原創文章 · 獲贊 1 · 訪問量 8219
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章