我一直在嘗試制作一個程式來為專案吐出單詞串列的定義。我正在使用https://dictionaryapi.dev/。我以前從未使用過 web api,所以我可以得到一些幫助。
var data = $.getJSON("https://api.dictionaryapi.dev/api/v2/entries/en/hello")
當時
我試過
了,document.getElementById('output').innerHTML = data.meanings[1].definition
但它不起作用。它說它找不到什么意思。
uj5u.com熱心網友回復:
您可以使用flatMap僅從回應中檢索定義:
const DICTIONARY_API_BASE_URL =
'https://api.dictionaryapi.dev/api/v2/entries/en/';
const DEFINITIONS_DIV = document.getElementById('definitions');
const fetchWordDefinitions = async word => {
console.log(`Making request for definitions of ${word}...`);
const response = await fetch(DICTIONARY_API_BASE_URL word);
const json = await response.json();
return json[0].meanings
.flatMap(m => m.definitions)
.flatMap(d => d.definition);
};
const getWordDefinitions = () => {
const word = document.getElementById('word').value;
if (word == null || word == '') {
return alert('Error: You must enter a word to fetch');
}
DEFINITIONS_DIV.innerHTML = '';
fetchWordDefinitions(word)
.then(defintions => {
defintions.forEach(d => {
DEFINITIONS_DIV.innerHTML = `<p>${d}</p>`;
});
})
.catch(_ => {
DEFINITIONS_DIV.innerHTML = `<p>Error: Could not retrive any defintions for ${word}.</p>`;
});
};
* {
font-family: sans-serif
}
<!DOCTYPE html>
<html>
<body>
<h1>Fetch the definitions for a word!</h1>
<input type="text" id="word" name="word">
<input type="button" value="Fetch" onClick="getWordDefinitions()">
<div id="definitions"></div>
</body>
</html>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/441714.html
標籤:javascript jQuery
上一篇:在Dropdown中動態添加選項
