const select1 = document.getElementById("select1");
const select2 = document.getElementById("select2");
const value1 = select1.options[select1.selectedIndex].value;
const value2 = select2.options[select2.selectedIndex].value;
fetch(https://api.example.com/${value1}/${value2}
)
.then(response => response.json())
.then(data => {
// 处理数据
})
const result = document.getElementById("result");
result.textContent = data.bestMatch;
完整代码示例:
const select1 = document.getElementById("select1");
const select2 = document.getElementById("select2");
const result = document.getElementById("result");
select1.addEventListener("change", getBestMatch);
select2.addEventListener("change", getBestMatch);
function getBestMatch() {
const value1 = select1.options[select1.selectedIndex].value;
const value2 = select2.options[select2.selectedIndex].value;
fetch(https://api.example.com/${value1}/${value2}
)
.then(response => response.json())
.then(data => {
result.textContent = data.bestMatch;
})
.catch(error => {
result.textContent = "Error: " + error.message;
});
}
注意:在代码示例中,我们使用了 addEventListener 方法来监听 select 元素的更改事件,以便在选择改变时获取新的值并请求 API。我们还添加了一个 catch 方法来处理错误。需要将 "https://api.example.com" 替换为实际的 API。
上一篇:遍历两个向量的R循环