我无法获取提取的JSON数据以显示在HTML网页中。数据很好,但是我无法显示它。我如何引入对象和数组一定是一个问题。
请协助。
const API_URL = 'https://api.unsplash.com/search/photos?page=1&client_id=00000000000';
const form = document.querySelector('form');
const input = document.querySelector('input');
const loadingImage = document.querySelector('#loadingImage');
const imageSection = document.querySelector('.image');
loadingImage.style.display = 'none';
form.addEventListener('submit', formSubmitted);
function formSubmitted(event) {
event.preventDefault();
const searchTerm = input.value;
searchStart();
search(searchTerm)
.then(displayImages)
.then(() => {
loadingImage.style.display = 'none';
});
}
function searchStart() {
loadingImage.style.display = '';
imageSection.innerHTML = '';
}
function search(searchTerm) {
const url = `${API_URL}&query=${searchTerm}`;
loadingImage.style.display ='';
return fetch(url)
.then(function(response) {
return response.json();
});
}
function displayImages (images) {
images.forEach(results => {
const imageElement = document.createElement('img');
imageElement.src = results[0].urls.full;
imageSection.appendChild(imageElement);
});
}
示例响应
{
"total": 8083,
"total_pages": 809,
"results": [
{
"id": "qY9zgRqmNtA",
"created_at": "2018-03-27T11:42:54-04:00",
"updated_at": "2018-08-28T20:56:16-04:00",
"width": 6435,
"height": 4290,
"color": "#FCFDFD",
"description": "people working inside white and black room",
"urls": {
"raw": "https://images.unsplash.com/photo-1522165078649-823cf4dbaf46?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjM4NDEyfQ&s=7d8696c868ca2cea4d2b337d0f42f6c1",
答案 0 :(得分:1)
根据结果数据的格式,您需要按以下方式更改displayImages
虽然我看不到每个条目都有一个名为full
的属性,但我想从原始代码中假定它是一个属性-如果将适当的数据示例放在问题本身中会更容易
function displayImages (result) {
result.results.forEach(img=> {
const imageElement = document.createElement('img');
imageElement.src = img.urls.full; // does full exist?
imageSection.appendChild(imageElement);
});
}
答案 1 :(得分:0)
{
"total": 8083,
"total_pages": 809,
"results": [
{
"id": "qY9zgRqmNtA",
"created_at": "2018-03-27T11:42:54-04:00",
"updated_at": "2018-08-28T20:56:16-04:00",
"width": 6435,
"height": 4290,
"color": "#FCFDFD",
"description": "people working inside white and black room",
"urls": {
"raw": "https://images.unsplash.com/photo-1522165078649-823cf4dbaf46?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjM4NDEyfQ&s=7d8696c868ca2cea4d2b337d0f42f6c1",