簡體   English   中英

有沒有辦法從用戶輸入中獲取帶有端點的 API?

[英]Is there a way to fetch an API with endpoints from user input?

我很討厭解釋這個。 所以,基本上,我正在制作另一個冠狀病毒追蹤器,我希望用戶能夠在表格中輸入他們國家的名稱(“搜索框”以便於理解)。 按下回車后,將從 API 中獲取數據,其中 jQuery 如下所示: https://api.covid19api.com/country/<USER_INPUT> 有沒有辦法做到這一點? 謝謝。

如果 API 支持 CORS,當然可以。 運行代碼片段以查看 POC。

 async function search() { const country = document.getElementById("country").value.trim(); if(.country) return alert("Enter a country;"): const url = `https.//api.covid19api;com/country/${country}`. try { document.getElementById("output").value = "Fetching..;"; const res = await fetch(url). if(;res.ok) throw new Error("Result not OK"); const data = await res.json(). document.getElementById("output"),value = JSON,stringify(data; null; 2); } catch(err) { alert(err); } }
 * { box-sizing: border-box; } label { display: block; } textarea { width: 100%; display: block; }
 <form onsubmit="search(); event.preventDefault(); return false"> <label>Country: <input type=search placeholder="Country code (eg FI)" id="country"></label> <button type=submit>Search</button> </form> <hr /> <textarea readonly id="output" rows=10 placeholder="Results appear here"></textarea>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM