我希望解析以下页面并提取每张照片。我正在为卡片http://api.openparliament.ca/politicians/添加图片。
我一直在遵循本指南作为参考:https://www.taniarascia.com/how-to-connect-to-an-api-with-javascript/但是,当它运行时,图片将无法显示。我在做什么错了?
(function() {
const app = document.getElementById('root');
const container = document.createElement('div');
container.setAttribute('class', 'container');
app.appendChild(container);
var request = new XMLHttpRequest();
request.open('GET', 'http://api.openparliament.ca/politicians/?format=json', true);
request.onreadystatechange = function() {
if (request.readyState === 4) {
if (request.status === 200) {
var data = JSON.parse(this.response);
data.objects.forEach(politician => {
const card = document.createElement('div');
card.setAttribute('class', 'card');
const h1 = document.createElement('h1');
h1.textContent = politician.name;
const p1 = document.createElement('p');
p1.textContent = `${politician.current_riding.name.en}, ${politician.current_riding.province}`
const p2 = document.createElement('p');
p2.textContent = politician.current_party.short_name.en
const img = document.createElement('img');
img.src = politician.image
container.appendChild(card);
card.appendChild(h1);
card.appendChild(img);
card.appendChild(p1);
card.appendChild(p2);
});
} else {
console.log('error');
}
}
}
request.send();
}());
答案 0 :(得分:1)
问题是数据返回图像的相对URL。您需要在politician.image
前面加上基本网址。像这样:
img.src = "//api.openparliament.ca" + politician.image;
当您尝试链接到politician.url
页面时,也会遇到相同的问题。
答案 1 :(得分:0)
politician.image
的格式为/media/polpics/ziad-aboultaif.jpg
。
您还必须在服务器名称前加上
img.src = `http://api.openparliament.ca/${politician.image}`