这个想法是,无论搜索什么内容,都会从单独的API中带回一些文本和图像。文本完全可以正常工作,但是图像没有出现。
完整的消息错误是:
未捕获的TypeError:无法在“节点”上执行“ appendChild”:参数1的类型不是“节点”。在Jdata.records.forEach.item和Array.forEach
request.addEventListener("load", function() {
if (request.status == 200) {
var Jdata = request.response;
Jdata.records.forEach(item => {
var results = document.getElementById("results");
var title = item.fields.title;
console.log(item.fields.title);
if (item.fields.hasOwnProperty('p_tag')) {
var fname = item.p_tag.substring(0,6);
var fid = item.fields.p_tag;
var image = `https://media.vam.ac.uk/media/thira/collection_images/${fname}/${fid}.jpg`;
var img2 = document.createElement('img');
img2.src = image;
}
else{
}
let h2 = document.createElement('h2');
h2.textContent = title;
results.appendChild(h2);
results.appendChild(img2);
})
} else {
console.log("error: "+xhr.status);
}
});
request.send();
答案 0 :(得分:0)
功能操作(){
var results = document.getElementById("results");
results.textContent = "";
console.log(results);
var sbar = document.getElementById("searchi").value;
console.log(sbar);
var request = new XMLHttpRequest;
var url = 'https://www.vam.ac.uk/api/json/museumobject/search?q='+sbar;
request.open('GET', url, true);
request.responseType ='json';
console.log("button was clicked");
request.addEventListener("load", function() {
if (request.status == 200) {
var Jdata = request.response;
Jdata.records.forEach(item => {
var results = document.getElementById("results");
var title = item.fields.title;
console.log(item.fields.title);
if (item.fields.hasOwnProperty('p_tag')) {
var fname = item.p_tag.substring(0,6);
var fid = item.fields.p_tag;
var image = `https://media.vam.ac.uk/media/thira/collection_images/${fname}/${fid}.jpg`;
var img2 = document.createElement('img');
img2.src = image;
}
else{
console.log("error");
}
let h2 = document.createElement('h2');
h2.textContent = title;
results.appendChild(h2);
results.appendChild(img2);
})
} else {
console.log("error: "+xhr.status);
}
});
request.send();
};