AJAX即“Asynchronous JavaScript and XML”
const request = new XMLHttpRequest()
request.open('get','xxx/xxx')
request.onreadyStateChange=function fn(){
if(request.readyState>=4){
console.log('请求完成')
if(request.response.state>=200 && request.response.state<300){
console.log('下载完成')
}else {
//下载失败
}
}
}
用fetch
发起请求:
返回一个Promise 通过then获取成功返回的结果
catch抓住请求的错误
<!DOCTYPE html>
<html lang="zh-Hans">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>CNodejs</h1>
<script>
fetch('https://cnodejs.org/api/v1/topics',{
method: 'GET', //GET/POST
mode: 'cors', //跨域
}).then(res => {
return res.json();
}).then(json => {
const a = document.createElement('div')
a.innerHTML = json.data.map(item => {
return `<h1>${item.title}</h1><div>${item.content}</div>`
})
document.body.appendChild(a)
console.log('获取的结果', json.data);
return json;
}).catch(err => {
console.log('请求错误', err);
})
</script>
</body>
</html>