当前位置: 首页 > news >正文

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

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

ajax与fetch对比

实现效果

请添加图片描述

代码实现

<!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封装

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实现的数据接口

  • 配置了跨域及解析前端请求数据的中间件
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");
});
  • 接口数据处理
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;

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

http://www.lryc.cn/news/507155.html

相关文章:

  • 安卓环境配置及打开新项目教程,2024年12月20日最新版
  • Docker 安装 禅道-21.2版本-外部数据库模式
  • 写SQL太麻烦?免费搭建 Text2SQL 应用,智能写 SQL | OceanBase AI 实践
  • 数据分析实战—鸢尾花数据分类
  • 【专题】2024抖音电商母婴行业分析报告汇总PDF洞察(附原数据表)
  • 堆栈粉碎的原理与预防攻击措施
  • Flutter组件————AppBar
  • 请问深度学习直接缝了别的模型,在论文中这种创新点应该如何描述呢?
  • 微流控专题 | 微流体应用说明——藻酸盐微球生产简介
  • 【前后端】HTTP网络传输协议
  • Fastdfs V6.12.1集群部署(arm/x86均可用)
  • 【LeetCode每日一题】——434.字符串中的单词数
  • windows C#-使用构造函数
  • [react]redux异步处理和重写useDispatch
  • 基础数据结构---栈
  • 【HarmonyOS之旅】DevEco Studio的安装与环境配置
  • Liveweb视频融合共享平台在果园农场等项目中的视频监控系统搭建方案
  • Android4.4 在系统中添加自己的System Service
  • 【C++】C++实现字符串大小写转换功能
  • 【蓝桥杯】43696.小数第n位
  • 进程间通信方式---消息队列(System V IPC)
  • windows10 安装wsl、迁移到其他盘
  • el-divide(vue3总)
  • python —— 常用命令行的命令
  • C++ 23版的最新特性
  • 什么是 Memory-bound stalls,以及如何优化
  • 机器学习 | 非线性回归拟合数据时的离群值检测
  • 使用elasticsearch-head插件修改elasticsearch数据
  • 202412月最新植物大战僵尸杂交版【V3.0.1】更新内容与下载
  • 游戏渠道假量解决方案