js使用ajax调用get接口/index
    		       		warning:
    		            这篇文章距离上次修改已过437天,其中的内容可能已经有所变动。
    		        
        		                
                在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来处理异步操作。两者都会在成功获取数据时在控制台中打印出响应。
评论已关闭