在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)似乎可行(innerHTL已更改) 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>

yinxilin 回答:在xmlHttp.onreadystatechange函数中设置“ innerHTML”时出错

@Gerard在评论中发布,这里的问题是JS if语句中缺少花括号。尴尬的...

本文链接:https://www.f2er.com/3117010.html

大家都在问