我刚开始学习 AJAX 并制作了一个简单的脚本。下面是脚本。
<!doctype html>
<html>
<head>
<title>Welcome to the forum</title>
<script>
var XMLHttpRequestObject = false;
if(window.XMLHttpRequest)
{
XMLHttpRequestObject = new XMLHttpRequest();
XMLHttpRequestObject.overrideMimeType("text/xml");
}
else
{
document.getElementById("text").innerHTML = "Sorry, your browser does not support AJAX!";
}
function getData(dataSource)
{
XMLHttpRequestObject.open("GET", dataSource);
XMLHttpRequestObject.onreadystatechange = function()
{
if(XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200)
{
responseData = XMLHttpRequestObject.responseXML;
responseDataList = responseData.getElementsByTagName("os");
}
}
XMLHttpRequestObject.send(null);
}
function displayMenuItems(dataSource,selectID)
{
getData(dataSource);
var i;
for(i=0; i<responseDataList.length; i++)
{
document.getElementById(selectID).options[i] = new Option(responseDataList[i].firstChild.data);
}
}
</script>
</head>
<body>
<form>
<select size="1" id="os">
<option>Select and OS</option>
</select>
<input type="button" value="Display OS list" onclick="displayMenuItems('os.xml','os')" />
</form>
<div id="text">The Operating System you use will appear here!</div>
</body>
当我单击按钮时,我期望在 HTML 列表中显示操作系统列表,但它仅在单击按钮两次后才会发生。我无法弄清楚问题是什么!:(
下面是 XML 脚本:
<?xml version="1.0"?>
<osList>
<os>Ubuntu</os>
<os>Fedora</os>
<os>Windows</os>
</osList>