如何从输入元素获取值并在异步获取函数中动态使用它?

问题描述 投票:0回答:1

在 url 中,这个词应该是动态的,但是当我使用

id=search
从输入标记获取值时。它返回 404 错误,但 api 链接是正确的。谁能帮助我完成 fetch api 中的任务

const meaning = document.querySelector("#meaning");
const button = document.querySelector("#button");

button.addEventListener('click', () => {
window.location.href = "/"
})

async function getWord() {
    const search = document.querySelector("#search").value;
    const url = `https://api.dictionaryapi.dev/api/v2/entries/en/${search}`
try {
    const getUrl = await fetch(url, {
        method: "GET",
    });
    // console.log(getUrl);
    const jsonUrl = await getUrl.json();
    console.log(jsonUrl);
    return jsonUrl
} catch (error) {
    alert("Please enter the correct word")
}
}
 
const word = await getWord();
console.log(word);

我无法理解我一直在搜索的单词的含义。

javascript api dictionary async-await fetch
1个回答
0
投票

您需要了解 GET 响应 JSON 文件。

数组和项目

[
开始。它意味着对象数据的
array
。 所以下一个字符将开始
{
。它意味着对象的第一项。

层次结构(父级 -> 子级 -> 孙级)

如果你想得到“大量的盐水”。定义

要检索它,此语法将得到它。

Data[0]["meanings"][0]["definitions"][0]["definition"]

准备工作

#1 安装 Chrome JSON Viewer 扩展程序,用于在 Chrome 中查看 JSON 数据

#2 VS Code 扩展 Live Server 用于运行 HTML 本地服务器

演示 HTML

另存为“word.html”

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dictionary App</title>
    <style>
        #meaning {
            margin-top: 20px;
        }
    </style>
</head>
<body>
    <input type="text" id="wordInput" placeholder="Enter a word">
    <button id="button">Get Meaning</button>
    <div id="meaning"></div>

    <script>
        const button = document.querySelector("#button");
        const meaning = document.querySelector("#meaning");

        button.addEventListener("click", async () => {
            const word = document.querySelector("#wordInput").value;
            const url = `https://api.dictionaryapi.dev/api/v2/entries/en/${word}`;

            try {
                const response = await fetch(url);
                const data = await response.json();

                displayMeanings(data);
            } catch (error) {
                meaning.innerHTML = `<p>Error fetching data: ${error.message}</p>`;
            }
        });

        function displayMeanings(data) {
            meaning.innerHTML = '';

            data.forEach(entry => {
                entry.meanings.forEach(meaningEntry => {
                    const partOfSpeech = document.createElement('h3');
                    partOfSpeech.textContent = meaningEntry.partOfSpeech;

                    meaning.appendChild(partOfSpeech);

                    meaningEntry.definitions.forEach(def => {
                        const definition = document.createElement('p');
                        definition.textContent = `Definition: ${def.definition}`;

                        meaning.appendChild(definition);

                        if (def.example) {
                            const example = document.createElement('p');
                            example.textContent = `Example: ${def.example}`;
                            example.style.fontStyle = 'italic';

                            meaning.appendChild(example);
                        }
                    });
                });
            });
        }
    </script>
</body>
</html>

运行 html

通过使用“word.html”从 VS Code 单击“上线”

通过 Chrome 打开

Enter `sea` word then press `Get Meaning` button

关系数据源、代码及展示

名称/值对的集合(通常以各种编程语言实现为对象)。 值的有序列表(通常实现为数组)。

当您有 JSON 数组时,您正在处理第二个结构:有序值列表。这些值可以是数字、字符串、布尔值、其他数组或对象。在 JavaScript 中,forEach() 方法通常用于迭代数组,包括 JSON 格式的数组。

以下详细介绍了如何使用 forEach() 从 JSON 数组中提取数据:

© www.soinside.com 2019 - 2024. All rights reserved.