我正在尝试让艺术家姓名以及其他字段在 HTML 页面中可见。从发布的代码中可以看到,图像已经显示在页面上,因此我们不太明白问题出在哪里。
window.addEventListener("load", function() {
document.getElementById('searchform').addEventListener('submit', search);
})
//load V&A museum objects
function search(evt) {
evt.preventDefault();
var query = document.getElementById('query').value.trim();
var url = "http://www.vam.ac.uk/api/json/museumobject/search?images=1&q=" + encodeURIComponent(query);
console.log(url);
var xhr = new XMLHttpRequest();
xhr.addEventListener("load", function() {
if (xhr.readyState == 4 && xhr.status == 200) {
var i, item, img_id, img_url, img, artist,
target = document.getElementById("result"),
json = JSON.parse(xhr.responseText);
console.log(json);
for (i = 0; i < json.records.length; i++) {
item = json.records[i];
console.log("artist = " + item.fields.artist);
img_id = item.fields.primary_image_id;
img_url = "http://media.vam.ac.uk/media/thira/collection_images/" +
img_id.substr(0, 6) +
"/" +
img_id +
"_jpg_o.jpg";
img = document.createElement("img");
img.setAttribute("src", img_url, );
target.appendChild(img);
artist = item.fields.artist;
artist = document.createElement("h1");
artist.setAttribute("h1", artist);
artist = document.createElement("br");
target.appendChild(artist);
}
}
});
xhr.open('GET', url, true); //true for asynchronous
xhr.send();
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="va.css">
<title>Victoria & Albert Museum API TEST</title>
<script src="va.js"></script>
</head>
<body>
<!--<button id="button">Search</button>
<br><br>
<h1>Museum Objects</h1>
<div id="objects"></div>-->
<form id="searchform" class="form">
<input type="text" id="query">
<input type="submit" id="button">
</form>
<div id="result" class="objects">
<!-- <div id="artists"><h1>Artists</h1></div> -->
</div>
</body>
</html>
结果是从 VA API 中提取图像,后跟艺术家姓名。图像可见,但艺术家只会打印到控制台。
最佳答案
我认为问题在于属性的设置,以及建议的艺术家的覆盖。
artistName = item.fields.artist;
artist = document.createElement("h1");
var newContent = document.createTextNode(artistName);
artist.appendChild(newContent);
target.appendChild(artist);
关于javascript - 将 JSON 记录注入(inject) HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47705059/