我收到以下错误
与我下面的代码
// 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
的内容我将脚本标签放在html as suggested by @Tejs here的底部,但仍然出现此错误。
最佳答案
执行回调时,页面上没有ID为“mainContent”的元素。
在该行中:
document.getElementById("mainContent").appendChild(p);
document.getElementById("mainContent")
部分返回null