无法设置null的属性'innerHTML'错误

时间:2013-09-12 12:01:02

标签: javascript ajax

我已经制作了一个非常基本和简单的代码,其中我有一个输入字段,在每个按键上都有效但是当我在表单中输入任何内容时没有任何反应,当我尝试使用chrome开发人员时这是错误 “无法设置属性'innerHTML'为null错误”

我不知道我做错了什么,我知道“document.getElementbyId('show')”返回null,但为什么?有人请帮助!谢谢你

这是我的index.html文件

<script type="text/javascript">
var xmlHttp = new XMLHttpRequest();   

function validate(user){               
        xmlHttp.open("GET", "names.php?name="+user, true);             
        xmlHttp.onreadystatechange = function(){
            document.write("error");
            document.getElementById('show').innerHTML = xmlHttp.responseText;
        }
        xmlHttp.send(null);
}

<h2>Enter a name :</h2>
<form>
<input type="text" onkeypress="validate(this.value)" />
<div id="show"></div>
</form>

4 个答案:

答案 0 :(得分:1)

问题在于这一行:

document.write("error");

在页面加载完成后使用document.write()时,它会终止当前页面,因此下一行'show'找不到document.getElementById('show')元素。

在我看来,你根本不需要document.write(),因为当你试图显示{{1}时,吐出硬编码的“错误”真的没有意义在一个div。如果确实需要显示错误,只需将其显示在该错误或其他div中,方法与响应文本相同。

答案 1 :(得分:1)

加载页面后请勿使用document.write,因为它会替换页面内容

答案 2 :(得分:1)

这是因为您正在使用document.write覆盖整个页面,因此“删除”div#show

请参阅:Why is document.write considered a "bad practice"?

答案 3 :(得分:0)

编辑:其他答案都是正确的 - document.write正在替换内容,因此该元素不再存在。这个答案的其余部分仍然有效!

据推测,您只想在请求完成时插入HTML;为此,请根据xmlHttp.readyState;

的值进行过滤
xmlHttp.onreadystatechange = function(){
    if (xmlHttp.readyState !== 4) { return; }
    document.getElementById('show').innerHTML = xmlHttp.responseText;
};
相关问题