Javascript 如何从选择框中获取值并使用它从API中获取响应?
我想做一个随机数事实应用程序,它是由一个数字的输入触发的。该应用程序运行良好,但我希望能够同时选择一个年份事实或一个数学事实,但它只显示数字事实,即使我选择了年份/数学。我使用的API允许我使用该格式(例如)。另外,我在JSlint中没有错误Javascript 如何从选择框中获取值并使用它从API中获取响应?,javascript,html,ajax,Javascript,Html,Ajax,我想做一个随机数事实应用程序,它是由一个数字的输入触发的。该应用程序运行良好,但我希望能够同时选择一个年份事实或一个数学事实,但它只显示数字事实,即使我选择了年份/数学。我使用的API允许我使用该格式(例如)。另外,我在JSlint中没有错误 let fact = document.querySelector("#fact"); let factText = document.querySelector("#factText"); let numberInput = document.query
let fact = document.querySelector("#fact");
let factText = document.querySelector("#factText");
let numberInput = document.querySelector("#numberInput");
let selecter = document.querySelector("#numberSelect");
numberInput.addEventListener("input", getFactAjax);
function getFactAjax() {
let xhr = new XMLHttpRequest();
let number = numberInput.value;
let numberType = "";
switch(selecter.value){
case 1:
numberType = "";
break;
case 2:
numberType = "/year";
break;
case 3:
numberType = "/math";
}
xhr.open("GET", "http://numbersapi.com/"+ number + numberType);
xhr.onload = function() {
if(this.status == 200 && number != ""){
fact.style.display = "block";
factText.innerHTML = this.responseText;
}
};
xhr.send();
};
input.value
返回一个字符串。使用严格相等运算符==
进行的比较返回字符串/整数比较的false
。switch语句使用严格相等。因此,当您在大小写中使用数字时,直接将从input.value
返回的字符串赋给switch语句时,没有一个大小写与给定的字符串匹配,整个过程基本上不起任何作用。简单的解决方案是在案例中使用字符串,例如案例“1”:
而不是案例1:
。“正确”的解决方案是首先将字符串转换为数字,例如使用parseInt
也发布html。我猜是选择器。值是字符串而不是整数。使用
onerror
尝试使用“case'1':…”等考虑因素,因为您使用的是onload
而不是onreadystatechange
。select元素的值为字符串,请在case语句中使用字符串。