ajax三中数据格式

xiaoxiao2022-06-12  43

欢迎访问: www.ptcms.cnajax中常用的三种数据格式分别为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>

转载请注明原文地址: https://www.6miu.com/read-4933373.html

最新回复(0)