ajax設定時間間隔內自動隨機讀取xml內容

    寫了個小功能,每隔5s自動讀取xml文件隨機內容,並輸出到瀏覽器終端.
javascript

    下面是xml文件內容: [這裏保存文件爲:testData.xml]php

<?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保存在同級目錄下]html

    [少許的DOM操做依賴jquery,這裏存放的目錄爲php腳本目錄下./js/jquery-2.0.3.js]java

    下面是php腳本,讀取xml文件後以json格式返回數據node

<?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()方法]
jquery

<!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>
相關文章
相關標籤/搜索