ajax设定时间间隔内自动随机读取xml内容

    写了个小功能,每隔5s自动读取xml文件随机内容,并输出到浏览器终端.

    下面是xml文件内容: [这里保存文件为:testData.xml]

<?xml version="1.0" encoding="utf-8"?>
<ServerList>
	<Group firstname="biby1" lastname="zhang1" sex="boy">
		<People age="24" company="oschina1"/>
		<People age="26" company="oschina2"/>
	</Group>
	<Group firstname="biby2" lastname="zhang2" sex="girl">
		<People age="24" company="oschina3"/>
	</Group>
	<Group firstname="biby3" lastname="zhang3" sex="middle">
		<People age="24" company="oschina4"/>
	</Group>
</ServerList>

    代码量很少,暂时把php代码直接嵌套在html中:[这里保存文件为readXml.php,并与testData.xml保存在同级目录下]

    [少量的DOM操作依赖jquery,这里存放的目录为php脚本目录下./js/jquery-2.0.3.js]

    下面是php脚本,读取xml文件后以json格式返回数据

<?php
if(!empty($_POST['name'])){
	$obj = new DOMDocument();
	$obj->load('./testData.xml');
	$infoData = $obj->getElementsByTagName("Group");
            
	$user = urldecode($_POST['name']);
	$data = array();
	$j = 0;
	foreach ($infoData as $value){
		$people = $value->getElementsByTagName("People");
		$len = $people->length;
		//第1个item:标签顺序  第2个item:属性顺序
		$name = $infoData->item($j)->attributes->item(0)->nodeValue;
		$j++;
		if($name!=$user) continue;
		for($i=0;$i<$len;$i++) {
			$data[$name][$i] = array();
			$data[$name][$i]['age'] = $people->item($i)->attributes->item(0)->nodeValue;
			$data[$name][$i]['company'] = $people->item($i)->attributes->item(1)->nodeValue;
		}

	}
	echo json_encode($data);
	exit();
}
?>

    下面是js脚本[这里用的是原生的XMLHttpRequest浏览器对象,没有使用jquery的$ajax()方法]

<!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" />
<script src="js/jquery-2.0.3.js" type="text/javascript"></script>
<title>xmlReader</title>
</head>
<body>
	<span id="showData"></span>
</body>
</html>

<script>
	var xmlhttp;
	if (window.XMLHttpRequest){
		xmlhttp=new XMLHttpRequest();//IE7+, Firefox, Chrome, Opera, Safari
	}else{
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");//IE6, IE5
	}
	function loadXMLDoc()
	{	
		var names = Array('biby1','biby2','biby3');
		var n=Math.floor(Math.random()*2);
		var name = 'name';
		var value = names[n];

		xmlhttp.onreadystatechange=function()
		{
			if (xmlhttp.readyState==4 && xmlhttp.status==200)
			{
				$("#showData").text(xmlhttp.responseText);
			}
		}
		
		xmlhttp.open("POST","?",true);
		xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
		xmlhttp.send(name+"="+value);
	}
	$(document).ready(function(){
		loadXMLDoc();
		window.setInterval("loadXMLDoc()",5000);
	});
</script>


你可能感兴趣的:(xml,PHP,Ajax)