我从JSON中提取数据并尝试在HTML中显示它。但它没有显示。我不知道导致错误的原因。请帮助我。看下面的代码
HTML CODE:
<body>
<section class="card">
<table class="table table-striped">
<thead>
<tr>
<th>Movies Name</th>
<th>Release Year</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</section>
<script type=text/javascript src="Script.js"></script>
JavaScript的:
function getMovies(cb){
const httpRequest=new XMLHttpRequest();
httpRequest.open('GET', "http://localhost:3000/movies");
httpRequest.onreadystatechange=function(){
if(httpRequest.readyState === XMLHttpRequest.DONE){
cb(null,JSON.parse(httpRequest.response));
}
};
httpRequest.send();
}
getMovies(function(err,movies) {
let td='',tr='';
let tbody=document.getElementsByTagName('tbody')[0];
tbody.innerHTML='';
let movie=movies[0];
let row=`
<th>${movie.name}</th>
<td>${movie.year}</td>
`;
let tr=document.createElement('tr');
tr.innerHTML=row;
});
答案 0 :(得分:1)
实际上更新DOM可能会有所帮助
let tr=document.createElement('tr');
tr.innerHTML=row;
之后
致电tbody.appendChild(tr)
如果没有任何变化,请尝试添加console.log(httpRequest.response)
,看看数据是否真的来了