2015-05-03 52 views
5

sto ottenendo il seguente erroreTypeError Uncaught: Impossibile leggere la proprietà 'AppendChild' di null

Uncaught TypeError: Cannot read property 'appendChild' of null

myRequest.onreadystatechange @ script.js:20

con il mio codice seguente

// 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> 

E qui è il mio file 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); 

Ed ecco il contenuto di simple.txt

This is the contents of a simple text file.

Ho inserito il tag script nella parte inferiore del codice HTML as suggested by @Tejs here ma sto ancora ricevendo questo errore.

+5

Sono abbastanza sicuro che il codice che si sta cercando non è la stessa come pubblicato qui. Perché va bene, nessun problema. http://plnkr.co/edit/cMsq1VNrr8stb8Oj4Xkb?p=preview – dfsq

+0

Non visualizza il contenuto di simple.txt sotto il mio tag h1. Inoltre ricevo l'errore nella console – Sparky

+0

Avevi ragione. Ho avuto un problema con i miei file. Sta lavorando adesso. Grazie – Sparky

risposta

8

Non c'è un elemento nella pagina con ID "mainContent" quando si esegue il callback.

Nella linea:

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

sezione document.getElementById("mainContent") sta tornando null

+0

Ho un ID chiamato mainContent nel mio html. Mi sto perdendo qualcosa? – Sparky

+0

Sto ricevendo lo stesso errore. – Sparky

+0

Grazie. Funziona ora. Ho avuto un mix con i miei file – Sparky

Problemi correlati