AJAX即“Asynchronous JavaScript and XML”

    1. const request = new XMLHttpRequest()
    2. request.open('get','xxx/xxx')
    3. request.onreadyStateChange=function fn(){
    4. if(request.readyState>=4){
    5. console.log('请求完成')
    6. if(request.response.state>=200 && request.response.state<300){
    7. console.log('下载完成')
    8. }else {
    9. //下载失败
    10. }
    11. }
    12. }

    fetch发起请求:
    返回一个Promise 通过then获取成功返回的结果
    catch抓住请求的错误

    1. <!DOCTYPE html>
    2. <html lang="zh-Hans">
    3. <head>
    4. <meta charset="UTF-8">
    5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
    6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
    7. <title>Document</title>
    8. </head>
    9. <body>
    10. <h1>CNodejs</h1>
    11. <script>
    12. fetch('https://cnodejs.org/api/v1/topics',{
    13. method: 'GET', //GET/POST
    14. mode: 'cors', //跨域
    15. }).then(res => {
    16. return res.json();
    17. }).then(json => {
    18. const a = document.createElement('div')
    19. a.innerHTML = json.data.map(item => {
    20. return `<h1>${item.title}</h1><div>${item.content}</div>`
    21. })
    22. document.body.appendChild(a)
    23. console.log('获取的结果', json.data);
    24. return json;
    25. }).catch(err => {
    26. console.log('请求错误', err);
    27. })
    28. </script>
    29. </body>
    30. </html>