fetch能够执行XMLHttpRequest所有任务,更容易使用,接口更现代化
fetch必须是异步的
获取响应
let r = fetch('weatherforecast') r.then((response) => { console.log(response)});
r.then(response => { //返回状态码200 console.log(response.status); //状态码在200-299之间时返回true console.log(response.ok); });
response.text获取数据
let r = fetch('weatherforecast') r.then((response) => { response.text().then(data => { console.log(data) }); });
简写
let r = fetch('weatherforecast') r.then(response => response.text()) .then(data => console.log(data));