[英]run a nested function on button click
我有一個 fetch API 從后端獲取響應,我在 fetch 中有一個 function 來提醒響應。 我要做的是在單擊按鈕時運行 function 但測試 function 不在全局 scope 上,因此我的按鈕無法訪問它來運行它。 有什么方法可以運行 function 以在收到響應后在按鈕單擊時提醒響應? 任何幫助表示贊賞。 提前致謝。
fetch(`http://localhost:PORT/api/ROUTE`).then(res => res.json()).then((response) => { function test() { alert(response) } })
<button onclick="test()">CLICK ME</button>
請注意,在您當前的代碼中, test
甚至沒有被then
回調調用。 將 function 移動到全局 scope 中,但請注意,無論如何,如果您單擊得太快,響應可能還不可用。 所以使用 promise:
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));
}
如果您的目的是在每次單擊按鈕時重做 fetch,那么將所有邏輯移到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));
}
如果要在獲取完成后顯示警報:
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 並啟動獲取。 獲取完成后,調用測試。 請注意,您可以進行多次點擊並讓 fetches 並行運行。
您需要在全局 scope 中聲明一個變量,並在獲取數據時為其分配一個 function。
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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.