使用Ajax发送网络请求
    		       		warning:
    		            这篇文章距离上次修改已过445天,其中的内容可能已经有所变动。
    		        
        		                
                在JavaScript中,可以使用原生的XMLHttpRequest对象或者更现代的fetchAPI来通过Ajax发送网络请求。以下是使用这两种方法的示例代码。
使用XMLHttpRequest的示例:
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.example.com/data", true);
xhr.onreadystatechange = function () {
  if (xhr.readyState == 4 && xhr.status == 200) {
    var response = JSON.parse(xhr.responseText);
    console.log(response);
  }
};
xhr.send();使用fetchAPI的示例:
fetch("https://api.example.com/data")
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));fetch API 是现代浏览器中推荐的方式,它提供了更好的语义和更灵活的链式调用方式。它返回一个Promise对象,可以使用.then()来处理响应,使用.catch()来处理错误。
评论已关闭