26_封装ajax.html 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>Document</title>
  7. </head>
  8. <body>
  9. <script src="./js/ajax.js"></script>
  10. <script>
  11. // function ajax(method,url,callback) {
  12. // // ajax 异步请求
  13. // // 第一步 实例化一个XMLHttpRequest对象
  14. // let xhr = new XMLHttpRequest();
  15. // // 第二步 调用open方法 配置请求参数
  16. // // open方法参数说明
  17. // // 第一个参数:请求方法 GET/POST
  18. // // 第二个参数:请求地址
  19. // // 第三个参数:是否异步 true/false
  20. // xhr.open(method, url, true);
  21. // // 第三步 调用send方法 发送请求
  22. // xhr.send();
  23. // // 第四步 监听状态变化
  24. // xhr.onreadystatechange = function () {
  25. // // 状态码 0 1 2 3 4
  26. // // 0: 请求未初始化 1: 服务器连接已建立 2: 请求已接收 3: 请求处理中 4: 请求已完成,且响应已就绪
  27. // if (xhr.readyState == 4) {
  28. // // 状态码 200 表示请求成功
  29. // if (xhr.status == 200) {
  30. // // 响应体
  31. // // console.log(xhr.responseText);
  32. // // 解析JSON字符串 转换为对象 调用JSON.parse方法
  33. // let jsonObj = JSON.parse(xhr.responseText);
  34. // // console.log(jsonObj);
  35. // // 访问对象属性
  36. // // console.log(jsonObj[0].url);
  37. // // 成功之后执行传递过来的回调函数
  38. // callback(jsonObj);
  39. // }
  40. // }
  41. // }
  42. // }
  43. // setTimeout 中第一个参数为回调函数 (成功之后再回来调用的函数)
  44. // 一般异步处理中都会使用回调函数
  45. // setTimeout(function(){
  46. // },1000)
  47. // ajax("GET","https://api.thecatapi.com/v1/images/searcha",function(res){
  48. // console.log(res);
  49. // });
  50. ajax("GET","./data/data1.json",function(res){
  51. console.log(res);
  52. ajax("GET","xxxxx",function(res){
  53. console.log(res);
  54. ajax("GET","yyyyy",function(res){
  55. console.log(res);
  56. })
  57. })
  58. });
  59. </script>
  60. </body>
  61. </html>