API

如何使用ajax

  • 1-1 HTML和CSS实现页面
  • 1-2 Ajax和Web服务器进行数据的异步交换
  • 1-3 运用JS操作DOM实现动态的局部刷新

    实现ajax

    1. <script>
    2. /* 实现ajax的前提
    3. 1.html页面
    4. 2.后端提供的数接口
    5. 3.DOM将获取的数据放在页面上 (有接口才有数据)*/
    6. var url = `http://127.0.0.1:5500/mock/index.json`;
    7. // 1.创建ajax的核心对象
    8. var xhr =new XMLHttpRequest();
    9. // 2.需要与服务器建立连接
    10. xhr.open("get",url,true)
    11. // 3.发送请求
    12. xhr.send();
    13. // 4.响应数据
    14. xhr.onreadystatechange =function(){
    15. if(xhr.readyState==4 && xhr.status==200){
    16. console.log(xhr.responseText)
    17. }
    18. }
    19. </script>

    9-2. 实现原生Ajax - 图1
    image.png

    封装ajax:

    1. function $ajax({url,success} ){
    2. var xhr = new XMLHttpRequest();
    3. xhr.open("get",url,true);
    4. xhr.send();
    5. xhr.onreadystatechange = function(){
    6. if (xhr.readyState ==4 && xhr.status>=200&&xhr.status<=300){
    7. var res = JSON.parse(xhr.responseText);
    8. success(res)
    9. }
    10. }
    11. }