【发布时间】:2017-08-11 08:55:41
【问题描述】:
我正在尝试使用 AJAX 动态构建此站点。我从 SQL 查询中加载“内容”div 的内容,具体取决于先前按下的按钮。 当我按下“Administrar”按钮时,我想在这个“adminButtonContainer”中添加一些按钮,但是显示如下错误:
'Cannot read property'innerHTML' of nullat XMLHttpRequest.ajaxResponse'
实际上,我只能在“内容”DIV 中添加新内容。我一直在阅读与加载每个 DIV 后调用 JavaScript 函数相关的内容,但我无法理解它。另外,如果可能的话,我想以一种“优雅”的方式来完成它:不必在类似的东西中添加标签。
这是我的 index.html 文件,我想保持简单:
<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”>
<html>
<head>
<title></title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="funciones.js"></script>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body onload="doAjaxQuery(1,1);">
<!-- LEFT MENU -->
<div class="leftMenu">
<!-- GENERAL BUTTONS -->
<div class="buttonContainer">
<button id="inicio" onclick="buttonPressed(1,0);">Inicio</button>
<button id="artistas" onclick="buttonPressed(2,0);">Artistas</button>
<button id="albumes" onclick="buttonPressed(3,0);">Álbumes</button>
<button id="temas" onclick="buttonPressed(4,0);">Temas</button>
<button id="generos" onclick="buttonPressed(5,0);">Géneros</button>
<button id="plataformas" onclick="buttonPressed(6,0);">Plataformas</button>
</div>
<!-- ONLY-ADMIN BUTTONS -->
<div class="adminButtonContainer">
<button onclick="doAjaxQuery(101,1)">Administrar</button>
</div>
</div>
<div id="content" class="content"></div>
</body>
</html>
这是正确写入“内容”DIV,但在任何其他 DIV 中引发错误的 JavaScript 函数:
function ajaxResponse() {
if (ajaxObject.readyState == 4) {
if (ajaxObject.status == 200) {
// JSON Decodification
var jsonResponse = JSON.parse(ajaxObject.responseText);
var contentDiv = document.getElementById("content");
var leftMenuDiv = document.getElementById("leftMenu");
var buttonsDiv = document.getElementById("buttonContainer");
var adminButtonsDiv = document.getElementById("adminButtonContainer");
// innerHTML works with contentDiv
setNewTitle(jsonResponse.Title);
contentDiv.innerHTML = "";
contentDiv.innerHTML += jsonResponse.H1;
contentDiv.innerHTML += jsonResponse.Body;
// innerHTML won't work with adminButtonsDiv (or any other but contentDiv):
// ERROR: 'Cannot read property 'innerHTML' of nullat XMLHttpRequest.ajaxResponse'
for (let boton of jsonResponse.BotonesAdmin) {
var bSeccion = boton[1];
var bBoton = boton[2];
adminButtonsDiv.innerHTML += bBoton;
}
} else {
document.write('There was an error. HTTP error code ' + ajaxObject.status.toString() + '.');
return;
}
}
}
【问题讨论】:
-
您自己进行一些研究,您会注意到
id丢失了。就像@Muthu Kumaran 注意到的那样:)
标签: javascript html innerhtml