ajax : 客户端向服务器端请求数据的一种技术

  1. 同步:客户端向服务器端发送请求的时候,用户不能进行其他操作
  2. 异步:客户端向服务器端发送请求的时候,用户可以进行其他操作
  3. 以及对资源的操作肯定是异步的

没封装的http

  1. <p id="app">
  2. </p>
  3. <script>
  4. /*
  5. 1.什么是异步 何时使用
  6. 2.如何使用原生ajax
  7. */
  8. var app = document.getElementById("app")
  9. var url ="http://192.168.4.18:8000/"
  10. /* ajax 如何使用ajax向后台获取数据*/
  11. /* 1. 创建ajax核心对象*/
  12. var xhr = new XMLHttpRequest();
  13. /* 2.与服务器建立连接 xhr.open(method,url,async)
  14. 请求的方式,地址,是否异步
  15. */
  16. xhr.open("get",url,true)
  17. /* 3.发送请求 */
  18. xhr.send()
  19. /* 4.响应 */
  20. /* onreadystatechange 监听服务器的响应状态*/
  21. xhr.onreadystatechange = function(){
  22. /* xhr.status 服务器端响应的状态码 200 */
  23. /* xhr.readyState 服务器响应的进度 4 响应已经完成 */
  24. if(xhr.readyState == 4 && xhr.status == 200){
  25. var txt = xhr.responseText;
  26. /* JSON.parse() 可以json格式的字符串,转换为json格式的数据 */
  27. var obj = JSON.parse(txt);
  28. console.log(obj)
  29. app.innerHTML = obj.name
  30. }
  31. }
  32. </script>

http.js

  1. function ajax({
  2. url,
  3. method,
  4. success
  5. }){
  6. var xhr = new XMLHttpRequest()
  7. xhr.open(method,url,true)
  8. xhr.send()
  9. xhr.onreadystatechange = function(){
  10. if(xhr.readyState == 4 && xhr.status == 200){
  11. var res = JSON.parse(xhr.responseText);
  12. success(res);
  13. }
  14. }
  15. }

传参(解构)

  1. function http({
  2. callback:callback,
  3. method,
  4. url,
  5. }) {
  6. console.log(callback);
  7. console.log(method)
  8. console.log(url)
  9. }
  10. http({
  11. callback:"123",
  12. method:"get",
  13. url:"xx"
  14. })

封装ajax

  1. <script src="js/http.js"></script>
  2. var url = "http://192.168.4.18:8000/"
  3. ajax({
  4. url,
  5. method:"get",
  6. success:res=>{
  7. console.log(res)
  8. }
  9. })

index.js

  1. const koa = require("koa");
  2. const app = new koa;
  3. const router = require("koa-router")();
  4. const cors = require("koa2-cors");
  5. app.use(cors());
  6. router.get("/",async ctx=>{
  7. ctx.body ={
  8. name:"html",
  9. age:13,
  10. code:200
  11. }
  12. })
  13. app.use(router.routes());
  14. app.listen(8000)