六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 35|回复: 0

ajax三中数据格式

[复制链接]

升级  36%

28

主题

28

主题

28

主题

秀才

Rank: 2

积分
104
 楼主| 发表于 2013-1-23 03:00:29 | 显示全部楼层 |阅读模式
欢迎访问: 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>

您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表