gpt4 book ai didi

javascript - 显示来自 fetch 方法的数据

转载 作者:行者123 更新时间:2023-12-03 03:23:09 25 4
gpt4 key购买 nike

我正在尝试获取用户在搜索输入中键入的内容的值,然后我想将此变量传递到我的端点并返回数据

                <input type="text" class="search" placeholder="planet">



<script>

const media = 'image';

const searchInput = document.querySelector('.search');
searchInput.addEventListener('change', searchData);


//get value of what is typed into search input.
function searchData() {
let search = this.value;
const finalData = getData(search);
}


// pass the search variable into the endpoint in getData function.
function getData() {
const endpoint = `https://images-api.nasa.gov/search?q=${search}&media_type=${media}`;
console.log(endpoint);

const result = [];

fetch(endpoint)
.then(blob => blob.json())
.then(data => result.push(...data.collection.items));
}

我不确定我这样做是否正确,或者是否有更好的替代方法,我对 JavaScript 还很陌生。谢谢。

最佳答案

给你

<input type="text" class="search" placeholder="planet">
<div class="output"></div>

<script>
const media = 'image';
const searchInput = document.querySelector('.search');
const output = document.querySelector('.output')

searchInput.addEventListener('change', searchData);

//get value of what is typed into search input.
async function searchData() {
let search = this.value;
const finalData = await getData(search);
render(finalData);
}

function render(data) {
output.innerHTML = JSON.stringify(data)
}


// pass the search variable into the endpoint in getData function.
function getData(search) {
const endpoint = `https://images-api.nasa.gov/search?q=${search}&media_type=${media}`;

return fetch(endpoint)
.then(blob => blob.json())
.then(data => data.collection.items);
}
</script>

在这里摆弄 https://jsfiddle.net/xyhk49wy/

您可以修改 render 函数,使其执行其他操作,而不是显示字符串化 JSON

关于javascript - 显示来自 fetch 方法的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46475520/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com