JavaScript网络请求Ajax
    		       		warning:
    		            这篇文章距离上次修改已过439天,其中的内容可能已经有所变动。
    		        
        		                
                在JavaScript中,可以使用XMLHttpRequest或现代的fetch API来进行网络请求,也称为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 json = JSON.parse(xhr.responseText);
    console.log(json);
  }
};
xhr.send();使用fetch API的例子:
fetch("https://api.example.com/data")
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));fetch API 是现代的、基于 Promise 的,并且提供了更好的异步处理流程。它也支持更现代的特性,如Request对象和Response对象,以及对HTTP的更好支持。
评论已关闭