这是用ajax做的一个小小的应用!当选择menu1的时候,会出来menu里面所有的内容。同理对于menu2.多的不说,代码如下:
首先是inner.html文件
<html>
<head>
<title>Using mutliple XMLHttpRequest objects</title>
<script language="javascript">
var menu;
function getmenu(menuNumber)
{
var XMLHttpRequestObject = false;
if(window.XMLHttpRequest)
{
XMLHttpRequestObject = new XMLHttpRequest();
XMLHttpRequestObject.overrideMimeType("text/xml");
}
else if (window.ActiveXObject)
{
XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}
if(XMLHttpRequestObject)
{
XMLHttpRequestObject.open("GET","menus.php?menu="+menuNumber);
XMLHttpRequestObject.onreadystatechange = function()
{
if( XMLHttpRequestObject.readyState == 4 &&XMLHttpRequestObject.status == 200)
{
var xmlDocument = XMLHttpRequestObject.responseXML;
menu = xmlDocument.getElementsByTagName("menuitem");
listmenu();
}
}
XMLHttpRequestObject.send(null);
}
}
function listmenu()
{
var loopIndex;
var selectControl = document.getElementById('menuList');
for(loopIndex = 0; loopIndex < menu.length; loopIndex++)
{
selectControl.options[loopIndex] = new Option(menu[loopIndex].firstChild.data);
}
}
function setmenu()
{
document.getElementById('targetDiv').innerHTML = "You selected " + menu[document.getElementById('menuList').selectedIndex].firstChild.data;
}
</script>
</head>
<body>
<h1>Using multiply XMLHttpRequest objects</h1>
<form>
<select size="1" id="menuList"onchange="setmenu()">
<option>Select a menu item</option>
</select>
<br>
<br>
<input type="button" value="Select menu 1"onclick = "getmenu('1')">
<input type="button" value="Select menu 2"onclick = "getmenu('2')">
</form>
<div id = "targetDiv" width=100 height=100>
Your lunch selection will appear here
</div>
</body>
</html>
其次就是menus.php文件:
<?php
header("Content-type:text/xml");
if($_GET["menu"] == "1")
$menuitems = array('Ham','Turkey','Beef');
if($_GET["menu"] == "2")
$menuitems = array('Tomato','Cucumber','Rice');
echo '<?xml version="1.0" ?>';
echo '<menu>';
foreach ($menuitems as $value)
{
echo '<menuitem>';
echo $value;
echo '</menuitem>';
}
echo '</menu>';
?>
这样的代码应该很容易看清楚吧。唯一不好的地方就是本人没写注释!