我正在尝试使用javascript获取并设置图片src,并且不断收到此错误,未捕获的TypeError:无法读取null的属性“ src”。我搜索了Stackoverflow,找不到解决方案。这是我的代码
<div class="modal fade" id="exampleModalLong" tabindex="-1" role="dialog" aria-labelledby="exampleModalLongTitle" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle"></h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="modalBody">
<img src="" id="modalImg">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
<script>
function viewProduct(product_id){
var request = new XMLHttpRequest();
request.open('GET', '/view_product_details/?product_id=' + product_id, true);
request.onreadystatechange = function(){
if (this.status == 200 && this.readyState == 4){
var data = JSON.parse(this.responseText);
console.log(data);
document.getElementById('exampleModalLongTitle').innerHTML = data.name
document.getElementById('modalBody').innerHTML = data.description
document.getElementById('img').setAttribute('src', data.image_url)
document.getElementById('img').src = data.image_url
}
}
request.send();
}
</script>
答案 0 :(得分:1)
您没有任何ID为img
的元素。唯一的图像对象的ID为modalImg
,那么您的getElementById应该是这样的:
document.getElementById('modalImg').setAttribute('src', data.image_url)
document.getElementById('modalImg').src = data.image_url