AJAX对于XML和JSON的处理

发布于:2025-06-04 ⋅ 阅读:(21) ⋅ 点赞:(0)

 这是book.xml文件:

<?xml version="1.0" encoding="ISO-8859-1"?>

<bookstore>

<book category="children">
  <title>Harry Potter</title> 
  <author>J K. Rowling</author> 
  <year>2005</year> 
  <price>29.99</price> 
</book>

<book category="cooking">
  <title lang="en">Everyday Italian</title> 
  <author>Giada De Laurentiis</author> 
  <year>2005</year> 
  <price>30.00</price> 
</book>

<book category="web">
  <title lang="en">Learning XML</title> 
  <author>Erik T. Ray</author> 
  <year>2003</year> 
  <price>39.95</price> 
</book>

<book category="web">
  <title lang="en">XQuery Kick Start</title> 
  <author>James McGovern</author> 
  <author>Per Bothner</author> 
  <author>Kurt Cagle</author> 
  <author>James Linn</author> 
  <author>Vaidyanathan Nagarajan</author> 
  <year>2003</year> 
  <price>49.99</price> 
</book>

</bookstore>

 这是处理XML的HTML文件:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script type="text/javascript">
// function readXML(){
// 	var xmlHttp;
//     if(window.ActiveXObject){
//       xmlHttp=new ActiveXObject("Microsoft.XMLHttp");
//     }else{
//       xmlHttp=new XMLHttpRequest();
//
//     }
// 	xmlHttp.open("GET","book.xml",false);
// 	xmlHttp.send();
// 	xmlDoc=xmlHttp.responseXML;
// 	books=xmlDoc.getElementsByTagName("book");
// 	alert(books.length);
// 	//alert(books[0].childNodes[0].nodeValue);
// 	for(i=0;i<books.length;i++){
// 		document.write(books[i].getElementsByTagName("title")[0].nodeName);
// 		document.write(": ");
// 		document.write(books[i].getElementsByTagName("title")[0].childNodes[0].nodeValue);
// 		document.write("&nbsp;&nbsp;&nbsp;&nbsp");
// 		document.write(books[i].getElementsByTagName("author")[0].nodeName);
// 		document.write(": ");
// 		document.write(books[i].getElementsByTagName("author")[0].childNodes[0].nodeValue);
// 		document.write("<br>");
// 	}
// }

function readXML(){
    var xmlhttp;
    if (window.ActiveXObject){
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }else{
        xmlhttp = new XMLHttpRequest();
    }
    xmlhttp.open("GET","book.xml",false);
    xmlhttp.send();
    xmlDoc = xmlhttp.responseXML;
    books = xmlDoc.getElementsByTagName("book");
    alert(books.length);
    //books[0]:获取 XML 文档中第一个 <book> 元素。
    //childNodes[0]:获取该 <book> 元素的第一个子节点(可能是文本节点或元素节点)。
    //nodeValue:获取该子节点的文本值。
    alert(books[0].childNodes[0].nodeValue);
    for (i=0;i<books.length;i++){
        document.write(books[i].getElementsByTagName("title")[0].nodeName);
        document.write(": ");
        document.write(books[i].getElementsByTagName("title")[0].childNodes[0].nodeValue);
        document.write("&nbsp;&nbsp;&nbsp;&nbsp");
        document.write(books[i].getElementsByTagName("author")[0].nodeName);
        document.write(": ");
        document.write(books[i].getElementsByTagName("author")[0].childNodes[0].nodeValue);
        document.write("&nbsp;&nbsp;&nbsp;&nbsp");
        document.write(books[i].getElementsByTagName("year")[0].nodeName);
        document.write(": ");
        document.write(books[i].getElementsByTagName("year")[0].childNodes[0].nodeValue);
        document.write("&nbsp;&nbsp;&nbsp;&nbsp");
        document.write(books[i].getElementsByTagName("price")[0].nodeName);
        document.write(": ");
        document.write(books[i].getElementsByTagName("price")[0].childNodes[0].nodeValue);
        document.write("<br>")
    }
}

</script>
</head>

<body>
<input type="button" value="读取XML" onclick="readXML();">
<span id="to">test</span>
</body>
</html>

这是处理json的处理方法:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script type="text/javascript">
function aa(){
	var stu='{"name":"zhangsan","age":18,"addr":{"priv":"zhejiang","city":"zhangzhou","zip":"310018"}}';
	var students='[{"name":"zhangsan","age":18},{"name":"li","age":20,"id":"2001"}]';
	
	var obj=eval('('+students+')');  //将一个 JSON 格式的字符串 转换为 JavaScript 对象
	alert(obj[1].name);
    var stu=eval('('+stu+')');
    alert(stu.addr.city);
}


function showJSON1() {  
	var user =  {  "username":"andy",  
					"age":20,  
					"info": { "tel": "123456", "cellphone": "98765"},  
					"address": [  
						{
							"city":"beijing",
							"postcode":"222333"
						},  
						{
							"city":"newyork",
							"postcode":"555666"
						}
						]  
				} 
	 
	alert(user.username);  
	alert(user.age);  
	alert(user.info.cellphone);  
	alert(user.address[0].city);  
	alert(user.address[0].postcode);  
	user.username = "Tom";  
	alert(user.username);  
}

function showJSON2(){
	var user='{"name":"tom","num":"2015001","dept":{"name":"computer","office":"综合8楼"},"addr":{"city":"宁波市","zip":"310018","street":"南京路111号"	}}';
				
	alert(user);
	var obj=eval('('+user+')');
	alert(obj.name);
	
}

function showJSON3() {  
	var users = [{  "username":"andy",  
					"age":20,  
					"info": { "tel": "123456", "cellphone": "98765"},  
					"address": [  
						{
							"city":"beijing",
							"postcode":"222333"
						},  
						{
							"city":"newyork",
							"postcode":"555666"
						}
						]  
				},
				{  "username":"tom",  
					"age":19,  
					"info": { "tel": "dsfdsf", "cellphone": "987ewrew65"},  
					"address": [  
						{
							"city":"nanjing",
							"postcode":"34343"
						},  
						{
							"city":"newyork",
							"postcode":"34343"
						}
						]  
				}
				]
				
	
	for(i=0;i<users.length;i++){
		document.write(users[i].username+" ");
		document.write(users[i].age +" ");
		document.write(users[i].info.tel +" ");
		document.write(users[i].address[0].city +users[i].address[0].postcode+" ");
		document.write("<br>");
	}
	
} 
</script>
</head>

<body>
<input type="button" value="test" onclick="aa();">
<input type="button" value="读取jason对象" onclick="showJSON1();">
<input type="button" value="读取jason字符串" onclick="showJSON2();">
<input type="button" value="读取jason数组" onclick="showJSON3();">
</body>
</html>

 这是菜鸟里的处理xml的方式:

<CATALOG>
<script/>
<CD>
<TITLE>Empire Burlesque</TITLE>
<ARTIST>Bob Dylan</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>Columbia</COMPANY>
<PRICE>10.90</PRICE>
<YEAR>1985</YEAR>
</CD>
<CD>
<TITLE>Hide your heart</TITLE>
<ARTIST>Bonnie Tyler</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>CBS Records</COMPANY>
<PRICE>9.90</PRICE>
<YEAR>1988</YEAR>
</CD>
<CD>
<TITLE>Greatest Hits</TITLE>
<ARTIST>Dolly Parton</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>RCA</COMPANY>
<PRICE>9.90</PRICE>
<YEAR>1982</YEAR>
</CD>
</CATALOG>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <style>
        table,th,td {
            border : 1px solid black;
            border-collapse: collapse;
        }
        th,td {
            padding: 5px;
        }
    </style>
</head>
<body>

<h1>XMLHttpRequest 对象</h1>

<button type="button" onclick="loadXMLDoc()">获取我收藏的 CD</button>
<br><br>
<table id="demo"></table>

<script>
    function loadXMLDoc() {
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                myFunction(this);  //这里的this.responseXML是XMLHttpRequest对象属性,返回 XML 文档。
            }
        };
        xhttp.open("GET", "https://www.runoob.com/try/demo_source/cd_catalog.xml", true);
        xhttp.send();
    }
    function myFunction(xml) {
        var i;
        var xmlDoc = xml.responseXML;
        var table="<tr><th>Artist</th><th>Title</th></tr>";
        var x = xmlDoc.getElementsByTagName("CD");
        for (i = 0; i <x.length; i++) {
            table += "<tr><td>" +
                x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue +
                "</td><td>" +
                x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue +
                "</td></tr>";
        }
        document.getElementById("demo").innerHTML = table;
    }
</script>

</body>
</html>

这是菜鸟的处理JSON响应数据的代码:

[
  {
    "title": "JavaScript 教程",
    "url": "https://www.runoob.com/js/"
  },
  {
    "title": "HTML 教程",
    "url": "https://www.runoob.com/html/"
  },
  {
    "title": "CSS 教程",
    "url": "https://www.runoob.com/css/"
  }
]
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script>
function loadXMLDoc()
{
  var xmlhttp;
  if (window.XMLHttpRequest)
  {
    // IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码
    xmlhttp=new XMLHttpRequest();
  }
  else
  {
    // IE6, IE5 浏览器执行代码
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function()
  {
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
	  var myArr = JSON.parse(this.responseText);  //将JSON数据格式解析为JS格式
      myFunction(myArr)
    }
  }
  xmlhttp.open("GET","/try/ajax/json_ajax.json",true);
  xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
  xmlhttp.send();
}
function myFunction(arr) {
  var out = "";
  var i;
  for(i = 0; i < arr.length; i++) {
    out += '<a href="' + arr[i].url + '">' + 
    arr[i].title + '</a><br>';
  }
 document.getElementById("myDiv").innerHTML=out;
}
</script>
</head>
<body>

<h2>AJAX JSON</h2>
<button type="button" onclick="loadXMLDoc()">请求 JSON 数据</button>
<div id="myDiv"></div>
 
</body>
</html>

网站公告

今日签到

点亮在社区的每一天
去签到