【原生js案例】ajax的简易封装实现后端数据交互

ajax是前端与后端数据库进行交互的最基础的工具,第三方的工具库比如jquery,axios都有对ajax进行第二次的封装,fecth是浏览器原生自带的功能,但是它与ajax还是有区别的,总结如下:

ajax与fetch对比

|----------------------------------------------------------------------------|
| |

实现效果

代码实现

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="./js/ajax.js"></script>
</head>
<body>
    <form action="" method="POST">
        <input type="text" name="" id="userInput" /> <br>
        <input type="text" name="" id="pwdInput" /> <br>
        <input type="button" value="提交" id="btn">
    </form>
    <div id="box"></div>
    <script>
       window.onload = function(){
          const oBtn = document.querySelector('#btn');
          const oInput = document.querySelector('#userInput');
          const oPwd = document.querySelector('#pwdInput');
          const oBox = document.querySelector('#box');
          oBtn.onclick = function(){
              if(oInput.value == ''){
                  alert('请输入内容');
              }else{
                http(`http://127.0.0.1:8080/api/user/form`,{name:oInput.value,pwd:oPwd.value},function(data){
                    oBox.innerHTML = `Hello ${data.data.name},欢迎你 ${data.data.pwd}`;
                },"POST")
              }
          }
       }
    </script>
</body>
</html>

ajax封装

js 复制代码
function http(url, data, cb, method = "GET") {
  const xhr = getXHR();
  console.log("🚀 ~ http ~ xhr:", xhr);
  xhr.open(method, url, true); // true为异步请求,false为同步请求
  xhr.onreadystatechange = function () {
    // 状态改变后执行此方法
    if (xhr.readyState === 4 && xhr.status === 200) {
      cb(JSON.parse(xhr.responseText)); // 字符创转成json
    }
  };
  xhr.setRequestHeader("Content-Type", "application/json");
  xhr.responseType = "application/json";
  xhr.send(method === "GET" ? null : JSON.stringify(data)); // 发送请求数据,GET方法不需要传递数据
}

//兼容处理
function getXHR() {
  let xhr = null;
  if (window.XMLHttpRequest) {
    xhr = new XMLHttpRequest();
  } else {
    xhr = new ActiveXObject("Microsoft.XMLHTTP");
  }
  return xhr;
}

node实现的数据接口

  • 配置了跨域及解析前端请求数据的中间件
js 复制代码
const express = require("express");
const userRouter = require("./routes/user");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();

// 允许跨域
app.use(cors());

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));

// parse application/json
app.use(bodyParser.json());

app.use("/api/user", userRouter);

app.listen(8080, () => {
  console.log("Server is running on port 8080");
});
  • 接口数据处理
js 复制代码
const express = require("express");

const router = express.Router();
// 模拟数据库,也可以介入mysql或者mongodb
const names = ["张三", "李四", "王五", "赵六"];

router.get("/", (req, res) => {
  res.send("Hello World!");
});

router.post("/form", (req, res) => {
  console.log("🚀 ~ router.post ~ req:", req.body);
  const { name, pwd } = req.body;
  if (names.includes(name)) {
    return res.json({
      code: 1,
      data: {
        name: "该用户名已经注册啦",
        pwd: "",
      },
    });
  } else {
    return res.json({
      code: 0,
      data: {
        name: `我是服务端返回的数据` + name,
        pwd: `我是服务端返回的数据` + pwd,
      },
    });
  }
});

module.exports = router;

这样,我们就可以实现前后端的数据交互了。

相关推荐
萌萌哒草头将军5 小时前
⚡⚡⚡尤雨溪宣布开发 Vite Devtools,这两个很哇塞 🚀 Vite 的插件,你一定要知道!
前端·vue.js·vite
游离状态的猫16 小时前
JavaScript性能优化实战:从瓶颈定位到极致提速
开发语言·javascript·性能优化
小彭努力中6 小时前
7.Three.js 中 CubeCamera详解与实战示例
开发语言·前端·javascript·vue.js·ecmascript
浪裡遊7 小时前
跨域问题(Cross-Origin Problem)
linux·前端·vue.js·后端·https·sprint
滿7 小时前
Vue3 Element Plus el-tabs数据刷新方法
javascript·vue.js·elementui
LinDaiuuj7 小时前
判断符号??,?. ,! ,!! ,|| ,&&,?: 意思以及举例
开发语言·前端·javascript
敲厉害的燕宝7 小时前
Pinia——Vue的Store状态管理库
前端·javascript·vue.js
Aphasia3117 小时前
react必备JavaScript知识点(二)——类
前端·javascript
玖玖passion7 小时前
数组转树:数据结构中的经典问题
前端
呼Lu噜7 小时前
WPF-遵循MVVM框架创建图表的显示【保姆级】
前端·后端·wpf