在 xmlHttp.onreadystatechange 函数中设置"innerHTML"时出错



我正在尝试编写一个JavaScript函数,从xmlHttp.onreadystatechange函数中更改段落的innerHTML。然而,Chrome控制台给了我一个错误:

Uncaught TypeError: Cannot set property 'innerHTML' of null
at XMLHttpRequest.xmlHttp.onreadystatechange (myfile.html:20)
at myfile.html:25

有两件事很有趣:1( 它似乎起作用(内部HTL已更改(2( 只有当我更改两个元素时,错误才会显示出来。

一旦我注释掉"document.getElementById"中的任何一行,一切似乎都很正常。

我被困在这里了。如果有人对可能出现的问题有任何意见,我们将不胜感激!

以下是完整的HTML代码(除了我更改的url变量(:

var url = "https://google.com"; // original URL replaced
var xmlHttp = new XMLHttpRequest();
// create XMLHttpRequest object
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
// this only works if one of the two following lines is removed
document.getElementById('id_hello1').innerHTML = "hello1";
document.getElementById('id_hello2').innerHTML = "hello2";
};
// open URL
xmlHttp.open("GET", url, true);
// send request
xmlHttp.send();
<h1>Hello1</h1>
<p id="id_hello1">loading...</p>
<h1>Hello2</h1>
<p id="id_hello2">loading...</p>

正如@Gerard在评论中发布的那样,这里的问题是JS if语句中缺少大括号。令人尴尬的