http.js

  1. //http.js
  2. /* 解构,回调函数
  3. 需要背诵
  4. */
  5. function ajax({
  6. url,
  7. method,
  8. success
  9. }){
  10. var xhr = new XMLHttpRequest()
  11. xhr.open(method,url,true)
  12. xhr.send()
  13. xhr.onreadystatechange = function(){
  14. if(xhr.readyState == 4 && xhr.status == 200){
  15. var res = JSON.parse(xhr.responseText);
  16. success(res);
  17. }
  18. }
  19. }

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)

ajax.html

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