【发布时间】:2020-01-04 15:30:46
【问题描述】:
我正在尝试了解如何使用异步/等待从外部 API 获取数据。我正在尝试从 openFDA API 获取数据。当用户输入药物时,API 检索数据并将其显示到网页上。输入值未传递给异步函数。
我看过其他教程,但它让我更加困惑。
//listens for the submit event and calls the getMeds function
const myForm = document.querySelector('#form').addEventListener('submit',getMeds);
// get the input value from the user
function getMeds(e){
const meds = document.querySelector('#searchbox').value;
console.log(meds);
e.preventDefault();
};
//get medication information from the OpenFDA API
const getMedicine = async (meds) => {
const base = 'https://api.fda.gov/drug/label.json';
const query = `?search=openfda.brand_name:${meds}%limit=5`;
const response = await fetch (base + query);
const data = await response.json();
return data
};
getMedicine()
.then(data => console.log(data))
.catch(err => console.log(err));
我希望 .json 对象显示在控制台中。到目前为止,它所做的是将输入值记录到控制台。
【问题讨论】:
标签: javascript async-await fetch-api