js使用ajax调用get接口/index
warning:
这篇文章距离上次修改已过187天,其中的内容可能已经有所变动。
在JavaScript中,您可以使用原生的XMLHttpRequest
对象或者现代的fetch
API来通过AJAX调用GET接口。以下是使用这两种方法的示例代码。
使用XMLHttpRequest
的示例:
var xhr = new XMLHttpRequest();
xhr.open("GET", "/index", true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
// 请求成功
var response = xhr.responseText;
console.log(response);
}
};
xhr.send();
使用fetch
API的示例:
fetch('/index')
.then(response => {
if (response.ok) {
return response.text();
}
throw new Error('Network response was not ok.');
})
.then(data => {
console.log(data);
})
.catch(error => {
console.error('There has been a problem with your fetch operation:', error);
});
在这两个示例中,我们都假设/index
是您要调用的GET接口的路径。当使用XMLHttpRequest
时,您需要监听onreadystatechange
事件,而使用fetch
时,您可以使用Promise
来处理异步操作。两者都会在成功获取数据时在控制台中打印出响应。
评论已关闭