在JavaScript中,要使用GET方法发送请求,您可以使用XMLHttpRequest
对象或更现代的fetch
API。以下是两种方法的示例:
方法1:使用XMLHttpRequest
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.responseText);
}
};
xhr.open("GET", "https://api.example.com/data", true);
xhr.send();
方法2:使用Fetch API
fetch("https://api.example.com/data")
.then(response => {
if (!response.ok) {
throw new Error("Network response was not ok");
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error("There was a problem with the fetch operation:", error));
请注意,fetch
API是现代浏览器中的一个较新功能,可能不支持较旧的浏览器。如果需要支持较旧的浏览器,可以考虑使用XMLHttpRequest
或引入一个polyfill,例如whatwg-fetch。
在使用XMLHttpRequest
时,onreadystatechange
事件处理程序会在请求的不同阶段触发。当readyState
为4且status
为200时,表示请求已成功完成。
在使用fetch
API时,您需要处理响应对象,检查响应是否成功(response.ok
),然后解析响应数据(例如,使用response.json()
)。
请根据您的需求和目标浏览器选择合适的方法。
领取专属 10元无门槛券
手把手带您无忧上云