Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
454 views
in Technique[技术] by (71.8m points)

javascript - Uncaught TypeError: Cannot read property 'appendChild' of null

I'm getting the following error

Uncaught TypeError: Cannot read property 'appendChild' of null

myRequest.onreadystatechange @ script.js:20

with my following code

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

And here is my JavaScript file

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

And here is the contents of simple.txt

This is the contents of a simple text file.

I put the script tag at the bottom of the html as suggested by @Tejs here but I'm still getting this error.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For people who have the same issue of querySelector or getElementById that returns the following error:

Uncaught TypeError: Cannot read property 'appendChild' of null

but you have a class name or id in the HTML...

If your script tag is in the head, the JavaScript is loaded before your HTML. You will need to add defer to your script like so:

<script src="script.js" defer></script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...