我收到以下错误
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的底部,但我仍然收到此错误.
解决方法
在执行回调时,页面上没有带有“mainContent”的元素.
在线:
document.getElementById("mainContent").appendChild(p);
部分document.getElementById(“mainContent”)返回null