respo-6ren">
gpt4 book ai didi

javascript - 将 json 数据导出到 fetch 范围之外

转载 作者:行者123 更新时间:2023-12-03 02:51:08 28 4
gpt4 key购买 nike

我正在尝试创建一个从 api 获取数据的简单示例。

fetch("https://api.example.com/results")
.then((response) => response.json())
.then(function(data) {
console.log(data)
});

现在,我的网页上有数据,但我想将数据“导出”到 fetch 之外,以便我可以根据表单过滤数据。有没有办法做到这一点?

最佳答案

正如 zabusa 所提到的,您可以创建一个执行过滤的函数,然后从 fetch 的 .then 链中调用该函数:

function filter(data) {
console.log("Filtering based on " + JSON.stringify(data))
// add the rest of your filtering code here
}

fetch("https://reqres.in/api/users/2")
.then((response) => response.json())
.then(function(data) {
filter(data)
});

您可能还想考虑使用 await,如下所示:

var response = await fetch("https://reqres.in/api/users/2")
var data = await response.json()
filter(data)

甚至:

filter(await (await fetch("https://reqres.in/api/users/2")).json())

关于javascript - 将 json 数据导出到 fetch 范围之外,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47856533/

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