2015-05-03 56 views
5

的 '使用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的底部,但我仍然收到這個錯誤。

+5

我敢肯定,因爲這裏發表您嘗試的代碼是不一樣的。因爲它很好,沒有問題。 http://plnkr.co/edit/cMsq1VNrr8stb8Oj4Xkb?p=preview – dfsq

+0

它不顯示我的h1標籤下面的simple.txt的內容。另外我得到控制檯中的錯誤 – Sparky

+0

你說得對。我混淆了我的文件。現在正在工作。謝謝 – Sparky

回答

8

當您的回調執行時,頁面上沒有ID爲「mainContent」的元素。

在行:

document.getElementById("mainContent").appendChild(p); 

部分document.getElementById("mainContent")正在返回null

+0

我在我的HTML中有一個名爲mainContent的id。我錯過了什麼? – Sparky

+0

我收到了同樣的錯誤。 – Sparky

+0

謝謝。它正在工作。我混合了我的文件 – Sparky

相關問題