未捕获的类型错误:不能设置属性'innerHTML'ajax中的null

Uncaught TypeError: Cannot set property 'innerHTML' of null in ajax

本文关键字:innerHTML ajax null 中的 属性 设置 类型 错误 不能      更新时间:2023-09-26

我只是一个试图学习一些AJAX的初学者,所以我的问题可能是愚蠢的。当我在浏览器中打开这个文档时,我点击页面上的按钮,得到错误"Uncaught TypeError: Cannot set property 'innerHTML' of null"。我试图解决这个问题,甚至删除了行与innerHTML属性和相同的错误涉及innerHTML不断出现,这是怎么可能的?如果你能帮忙,我会很感激的。

    <!doctype html>
<html>
<head>
    <script type="text/javascript">
    function cargaXML(){
        var conexion;
        var txt,x,i;
        if(window.XMLHttpRequest){
                        conexion = new XMLHttpRequest();
                    } else {
                        conexion = new ActiveXObject("Microsoft.XMLHTTP");
                    }

        conexion.onreadystatechange = function(){
            if (conexion.readyState == 4 && conexion.status == 200){
                xmlDoc = conexion.responseXML;
                txt = "<table>";
                x = xmlDoc.getElementsByTagName("titulo");
                artista = xmlDoc.getElementsByTagName("artista");
                pais = xmlDoc.getElementsByTagName("pais");
                firma = xmlDoc.getElementsByTagName("firma");
                precio = xmlDoc.getElementsByTagName("precio");
                anio = xmlDoc.getElementsByTagName("anio");
                for (i=0;i<x.length;i++){
                    txt = txt + "<tr><td>" + x[i].childNodes[0].nodeValue + "</td><tr>" + artista[i].childNodes[0].nodevalue + "</td><td>" + pais[i].childNodes[0].nodevalue + "</td><td>" + firma[i].childNodes[0].nodevalue + "</td><td>" + precio[i].childNodes[0].nodevalue + "</td><td>" + anio[i].childNodes[0].nodevalue + "</td>";
                }
                txt = txt + "</table>";
                document.getElementById("myDiv").innerHTML = txt;
            }
            conexion.open("GET","discos.xml",true);
            conexion.send();
        }
        }
    </script>
</head>
<body>
    <h2>Mi colección</h2>
    <div id="myDiv">

    </div>
    <button type="button" onclick="cargaXML()">Tomar mi colección</button>
</body>
</html>

问题是javascript在div "myDiv"被打印到页面之前正在运行。通常这可以通过使用jQuery和$(document)来纠正。准备好了电话。在javascript中,你可以在window:

上使用onload属性

窗口。

尝试将所有内容放在按钮下方的script标签中,因为页面中的所有内容都按照逻辑顺序加载,因此

    JavaScript

它试图在渲染之前访问HTML标签所以它应该进入

  • JavaScript

或在整个脚本周围添加body onload,以便在尝试使用它之前等待文档加载