【发布时间】:2021-05-30 12:08:32
【问题描述】:
我正在尝试获取此 API 返回的结果并将其打印到一个简单的 HTML 元素中,以便用户可以阅读。目前它设置为将所有值返回到控制台日志。到目前为止,我已经尝试在 HTML 中创建一个 div 元素并在那里打印数据,我也尝试过使用 innerHTML 但我也没有成功使用该方法。
<body>
<form id="form1" runat="server">
<div>
<br />
<input id="myfiles" type="file" multiple="multiple" />
<button type="button">OK</button>
<button id="MyButton" type="button" onclick="sendIdentification()">OK</button>
</div>
<div id="displayresult">
<p>Result here</p>
</div>
</form>
<script type="text/javascript">function sendIdentification() {
alert('start');
const files = [...document.querySelector('input[type=file]').files];
const promises = files.map((file) => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = (event) => {
const res = event.target.result;
console.log(res);
resolve(res);
}
reader.readAsDataURL(file)
})
})
Promise.all(promises).then((base64files) => {
console.log(base64files)
const data = {
api_key: "Die8ewFGvpw5JrRTuOEjgGR10uLjMwirF3jYaalmRjk4dzP8Gm",
images: base64files,
modifiers: ["crops_fast", "similar_images"],
plant_language: "en",
plant_details: ["common_names",
"url",
"name_authority",
"wiki_description",
"taxonomy",
"synonyms"]
};
fetch('https://api.plant.id/v2/identify', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
})
/* attempt to try parsing to an html element in addition to the console log. Currently throws an error.
document.querySelector('#displayresult').innerHTML = jsonData[1].common_names);
for (var i = 0; i < jsonData.length; i++) {
document.querySelectorAll('.displayresult')[i].innerHTML = jsonData[i].common_names;
*/
}
};</script>
【问题讨论】:
标签: javascript html arrays json parsing