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

前端之家收集整理的这篇文章主要介绍了ajax设定时间间隔内自动随机读取xml内容前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

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

<?xmlversion="1.0"encoding="utf-8"?>
<ServerList>
	<Groupfirstname="biby1"lastname="zhang1"sex="boy">
		<Peopleage="24"company="oschina1"/>
		<Peopleage="26"company="oschina2"/>
	</Group>
	<Groupfirstname="biby2"lastname="zhang2"sex="girl">
		<Peopleage="24"company="oschina3"/>
	</Group>
	<Groupfirstname="biby3"lastname="zhang3"sex="middle">
		<Peopleage="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=newDOMDocument();
	$obj->load('./testData.xml');
	$infoData=$obj->getElementsByTagName("Group");

	$user=urldecode($_POST['name']);
	$data=array();
	$j=0;
	foreach($infoDataas$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;
		}

	}
	echojson_encode($data);
	exit();
}
?>

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

<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<htmlxmlns="http://www.w3.org/1999/xhtml">
<head>
<Metahttp-equiv="Content-Type"content="text/html;charset=utf-8"/>
<scriptsrc="js/jquery-2.0.3.js"type="text/javascript"></script>
<title>xmlReader</title>
</head>
<body>
	<spanid="showData"></span>
</body>
</html>

<script>
	varxmlhttp;
	if(window.XMLHttpRequest){
		xmlhttp=newXMLHttpRequest();//IE7+,Firefox,Chrome,Opera,Safari
	}else{
		xmlhttp=newActiveXObject("Microsoft.XMLHTTP");//IE6,IE5
	}
	functionloadXMLDoc()
	{	
		varnames=Array('biby1','biby2','biby3');
		varn=Math.floor(Math.random()*2);
		varname='name';
		varvalue=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>
原文链接:https://www.f2er.com/ajax/165069.html

猜你在找的Ajax相关文章