的 '使用appendChild' 我發現了以下錯誤遺漏的類型錯誤:無法讀取屬性空
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
的內容
This is the contents of a simple text file.
我把腳本標籤放在html as suggested by @Tejs here的底部,但我仍然收到這個錯誤。
我敢肯定,因爲這裏發表您嘗試的代碼是不一樣的。因爲它很好,沒有問題。 http://plnkr.co/edit/cMsq1VNrr8stb8Oj4Xkb?p=preview – dfsq
它不顯示我的h1標籤下面的simple.txt的內容。另外我得到控制檯中的錯誤 – Sparky
你說得對。我混淆了我的文件。現在正在工作。謝謝 – Sparky