我有一个从后端获取响应的fetch API,并且我在fetch中有一个函数来警告响应。我试图做的是单击一个按钮运行函数,但测试函数不在全局范围内,因此我的按钮无法访问它来运行它。有没有办法在得到响应后,运行函数在按钮点击时向响应发出警告?任何帮助都是非常感谢的。提前谢谢。
fetch(`http://localhost:PORT/api/ROUTE`)
.then(res => res.json())
.then((response) => {
function test() {
alert(response)
}
})<button onclick="test()">CLICK ME</button>
发布于 2021-06-04 13:56:12
请注意,在您当前的代码中,then回调甚至没有调用test。将该函数移动到全局作用域中,但请注意,无论如何,如果您单击得太快,响应可能还不可用。因此,请按照承诺工作:
let promise = fetch(`http://localhost:PORT/api/ROUTE`)
.then(res => res.json());
test(); // Optional -- if you want to have the alert even when button is not clicked.
function test() {
promise.then(response => alert(response));
}如果您的目的是在每次单击按钮时重做获取,那么将所有逻辑移动到test中。
test(); // Optional -- when you want to initiate the fetch on page load
function test() {
fetch(`http://localhost:PORT/api/ROUTE`)
.then(res => res.json());
.then(response => alert(response));
}发布于 2021-06-04 13:56:34
如果要在抓取完成后显示警报:
function getdata() {
fetch(`http://localhost:PORT/api/ROUTE`)
.then(res => res.json())
.then((response) => {
function test() {
alert(response)
}
})
}
<button onclick="getdata()">CLICK ME</button>调用getdata并启动fetch。获取完成后,将调用test。请注意,您可以进行多次单击,并并行运行抓取。
发布于 2021-06-04 14:00:45
您需要在全局范围内声明一个变量,并在获取数据时为其分配一个函数。
var test;
fetch(`https://api.github.com/users/techysharnav/repos`) //For Test purposes
.then(res => res.json())
.then((response) => {
test = (response)=>alert(response)
})<button onclick="test()">CLICK ME</button>
https://stackoverflow.com/questions/67832061
复制相似问题