我正在尝试使用AJAX动态构建本网站。我从SQL查询中加载“内容”div的内容,具体取决于以前按下的按钮。 当我按下“Administrar”按钮,我想在某些按钮添加到这个“adminButtonContainer”,但会显示以下错误:
“不能读取属性‘’nullat XMLHttpRequest.ajaxResponse的” innerHTML的
事实上,我只能将新内容添加到“内容”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的JavaScript函数,而是抛出一个错误在任何其它DIV:
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注意到的:) – Red