这是由于我的代码出现了问题。Uncaught TypeError: Cannot read property 'appendChild' of null
myRequest.onreadystatechange @ script.js:20
// index.html
<html>
<head>
<title>Simple Page</title>
</head>
<body>
<div id="mainContent">
<h1>This is an AJAX Example</h1>
</div>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
这是我的JavaScript文件
// script.js
// 1. Create the request
var myRequest;
// feature check!
if(window.XMLHttpRequest) { // Firefox, Safari
myRequest = new XMLHttpRequest();
} else if (window.ActiveXObject){ // IE
myRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
// 2. Create an event handler for our request to call back
myRequest.onreadystatechange = function() {
console.log("We were called!");
console.log(myRequest.readyState);
if(myRequest.readyState === 4){
var p = document.createElement("p");
var t = document.createTextNode(myRequest.responseText);
p.appendChild(t);
document.getElementById("mainContent").appendChild(p);
}
};
// 3. open and send it
myRequest.open("GET","simple.txt", true);
// any parameters?
myRequest.send(null);
以下是simple.txt
的内容:
这是一个简单文本文件的内容。
我按照@Tejs在这里的建议,将脚本标签放在html底部,但我仍然遇到了这个错误。