1、原生js

  1. var url = `http://127.0.0.1:5500/mock/index.json`
  2. /* 1、创建ajax的核心对象 */
  3. var xhr = new XMLHttpRequest();
  4. /* 2、需要与服务器建立连接 */
  5. xhr.open("get", url, true)
  6. /* 3、发送请求 */
  7. xhr.send();
  8. /* 4、响应数据 */
  9. /* onreadystatechange监听服务器状态的变化 */
  10. xhr.onreadystatechange = function () {
  11. // readystate值代表服务器响应的变化 ==4 请求完成,响应准备就绪
  12. /* status==200请求成功,数据成功的响应 */
  13. if (xhr.readyState == 4 && xhr.status == 200) {
  14. var res = JSON.parse(xhr.responseText)
  15. console.log(res)
  16. }
  17. }

2、ajax.js

  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){
  7. var res = JSON.parse(xhr.responseText);
  8. success(res)
  9. }
  10. }
  11. }
  1. <script src="lib/ajax.js"></script>
  2. </head>
  3. <body>
  4. <script>
  5. var url = 'http://47.108.197.28:8000/book';
  6. $ajax(url,res=>{
  7. console.log(res)
  8. })
  9. </script>
  10. </body>

3、obj-ajax.js

  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){
  7. var res = JSON.parse(xhr.responseText);
  8. success(res)
  9. }
  10. }
  11. }
  1. <script src="lib/obj-ajax.js"></script>
  2. </head>
  3. <body>
  4. <script>
  5. var url = 'http://47.108.197.28:8000/book';
  6. $ajax({
  7. url,
  8. success:res=>{
  9. console.log(res)
  10. }
  11. })
  12. </script>
  13. </body>