-1
當我嘗試使用AJAX顯示xml文件時,我的.html文件中出現錯誤。我的程序應該有一個可以讀取json文件的按鈕和另一個可以讀入xml文件的按鈕。 json按鈕工作得很好,但按下按鈕時,xml按鈕會給我一個錯誤,我無法弄清楚。使用AJAX在XML文件中讀取時出錯
,我在
Uncaught TypeError: Cannot set property 'innerHTML' of null index.html:34
這裏正的錯誤是我的代碼:
的index.html
<!DOCTYPE html>
<html>
<head>
<title>AJAX - responseJSON</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.overrideMimeType("text/xml")
xmlHttp.send();
}
function getContent() {
var xmlHttp = xmlHttpObjCreate();
if (!xmlHttp) {
alert("The browser doesn't support this action.");
return;
}
xmlHttp.onload = function() {
if (xmlHttp.status == 200) {
// Get Response Text
var response = xmlHttp.responseText;
// Prints the JSON string
console.dir(response);
// Get div object
var divObj = document.getElementById('contentBox');
// We used JSON.parse to turn the JSON string into an object
var responseObject = JSON.parse(response);
// This is our object
console.dir(responseObject);
// We can use that object like so:
divObj.innerHTML = "Hi I am " + responseObject.name + " and my pet is " + responseObject.pet;
}
}
xmlHttp.open("GET", "json.php", true);
xmlHttp.send();
}
</script>
</head>
<body>
<h3>My Content</h3>
<div id="contentBox"></div>
<button type="button" onclick="getContent();">Get Content</button>
<h3>My movies</h3>
<div id"movieBox"></div>
<button type="button" onclick="getMovies();"> Get Movies</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>