我对如何使用AJAX从.xml文件中读取信息感到困惑。我希望程序执行的只是显示用户可以按下的按钮,然后它将在.xml文件中显示电影列表。现在我的网页显示按钮,但当用户按下它时没有任何反应。我将发布我的3个文件,希望有人可以帮助我。
的index.html
<!DOCTYPE html>
<html>
<head>
<title>AJAX - responseXML</title>
<script src="ajax.js"></script>
<script>
function getMovies() {
var xmlHttp = xmlHttpObjCreate();
if (!xmlHttp) {
alert("The browser doesn't support this action.");
return;
}
xmlHttp.onload = function() {
if (xmlHttp.status == 200) {
// Get XML Document
var xmlDoc = xmlHttp.responseXML;
// Variable for our output
var output = '';
// Build output by parsing XML
movieTitles = xmlDoc.getElementsByTagName('title');
for (i = 0; i < movieTitles.length; i++) {
output += movieTitles[i].childNodes[0].nodeValue + "<br>";
}
// Get div object
var divObj = document.getElementById('movieBox');
// Set the div's innerHTML
divObj.innerHTML = output;
}
}
xmlHttp.open("GET", "movies.xml", true);
xmlHttp.send();
}
</script>
</head>
<body>
<h3>My Movies</h3>
<div id="movieBox"></div>
<button type="button" onclick="getMovies()">Get Movie Titles</button>
</body>
</html>
ajax.js
function xmlHttpObjCreate() {
var xmlHttp;
try
{xmlHttp=new XMLHttpRequest();
}
catch (e)
{try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
return false;
}
}
}
return xmlHttp;
}
movies.xml
<?xml version= "1.0"?>
<collection>
<movies>
<title> Gone with the Wind
<year> 1939 </year>
</title>
<title> 2001: A Space Odyssey
<year> 1968 </year>
</title>
<title> Jurassic Park
<year> 1993 </year>
</title>
<title> The Shawshank Redmption
<year> 1994 </year>
</title>
<title> Balto
<year> 1995 </year>
</title>
</movies>
</collection>
这是我得到的错误
Uncaught TypeError: Cannot read property 'getElementsByTagName' of null