【发布时间】:2015-07-12 21:24:27
【问题描述】:
我收到以下错误
未捕获的类型错误:无法读取 null 的属性“appendChild”
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的内容
这是一个简单文本文件的内容。
我将脚本标签放在 html as suggested by @Tejs here 的底部,但我仍然收到此错误。
【问题讨论】:
-
它不会在我的 h1 标签下显示 simple.txt 的内容。另外,我在控制台中收到错误
-
你是对的。我把我的文件弄混了。它现在正在工作。谢谢
标签: javascript ajax