//get查看
router.get("/fruits", ctx => {
ctx.body = dataList;
})
//post添加
router.post("/fruits", ctx => {
let fruit = ctx.request.body.fruit;
dataList.push(fruit);
ctx.body = dataList;
})
数据是存在服务器的内存里面的,服务器重启的话数据就会消失 push(数组末尾添加)
//put修改
router.put("/fruits/:id", ctx => {
let id = ctx.params.id;
let fruit = ctx.request.body.fruit;
dataList.splice(id, 1, fruit);
ctx.body = dataList;
})
/fruits/:id 路由传参数 由ctx.params.id可以取得 splice(删除元素的索引,删除几个元素,将删除的元素替换成xxx)
//delete删除
router.delete("/fruits/:id", ctx => {
let id = ctx.params.id;
dataList.splice(id, 1);
ctx.body = dataList;
})
在我们之前学习的内容中,向服务器发送请求后,再浏览器中响应的页面都是整页刷新。
在某些项目中,我们只希望获取页面的局部数据,而不必整页刷新,这个时候就需要使用Ajax来实现功能了。
Ajax 的全称是Asynchronous JavaScript and XML(异步的JavaScript 和 XML)。这个概念出现的比较早,那个时候前端和后台的数据交互主要以XML格式为主。现在仍然存在很多用xml交互数据的情况,但是目前主流的数据格式使用的是json(JavaScript对象表示法)
考虑一个问题,在之前的学习内容中,我们是如何向服务器发送请求的?这里我们列举一下:
在浏览器中直接输入网址 a标签实现的页面跳转 表单提交 Postman模拟http请求
Ajax的原理是通过XMLhttpRequest对象向服务器发送请求,实例代码如下所示:
const Koa = require("koa");
const router = require("koa-router")();
const nunjucks = require("nunjucks");
const views = require("koa-views");
const app = new Koa();
app.use(views(__dirname + '/views', {
map: { html: 'nunjucks' }
}));
router.get("/", async ctx => {
await ctx.render("index")
})
router.get("/data", async ctx => {
ctx.body = "hello world"
})
app.use(router.routes())
app.listen(3000, () => {
console.log("server is running");
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>首页</h1>
<button>get</button>
</body>
<script>
document.querySelector("button").onclick = function () {
let xhr = new XMLHttpRequest();
//用xhr这个对象来向服务器发送请求
xhr.open("get", "/data"); //规定请求类型
xhr.send() //发送请求
xhr.onreadystatechange = function () { //监听readyState事件
// 0: 请求未初始化
// 1: 服务器连接已建立
// 2: 请求已接收
// 3: 请求处理中
// 4: 请求已完成,且响应已就绪
if (xhr.readyState === 4 && xhr.status === 200) {
alert(xhr.responseText)
}
}
}
</script>
</html>
用xhr这个对象来向服务器发送请求 xhr.onreadystatechange xhr的readystate属性值改变时触发 status是状态码(404啥的),200是正常 可麻烦,其实不用写,直接调库
封装一个Ajax方法 回调函数 将上面的程序封装到一个myAjax方法,实例代码如下所示,这里需要注意的是,因为Ajax是异步的操作,因此封装的Ajax不能用return获取返回值。下面的示例使用的是回调函数封装的Ajax方法
document.querySelector("button").onclick = function () {
myAjax("get", "/data");
}
function myAjax(method, URL) {
let xhr = new XMLHttpRequest();
xhr.open(method, URL); //规定请求类型
xhr.send() //发送请求
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
alert(xhr.responseText)
}
}
}
你要是实在想return,可以写一个回调函数
document.querySelector("button").onclick = function () {
myAjax("get", "/data", function (res) {
alert(res);
});
}
function myAjax(method, URL, next) {
let xhr = new XMLHttpRequest();
xhr.open(method, URL);
xhr.send()
let result = ""
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
next(xhr.responseText);
}
}
}
过多的使用回调函数会让程序变得很难维护,接下来我们用Promise重新封装ajax方法,示例代码如下所示:
document.querySelector("button").onclick = function () {
myAjax("get", "/data").then(res => {
alert(res);
}
);//此时return了一个promise对象
}
function myAjax(method, URL) {
return new Promise(function (resolve) {
let xhr = new XMLHttpRequest();
xhr.open(method, URL);
xhr.send()
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
resolve(xhr.responseText);
}
}
})}
我tm直接一知半解
调库
const Koa = require("koa");
const router = require("koa-router")();
const nunjucks = require("nunjucks");
const views = require("koa-views");
const static = require("koa-static");
const parser = require('koa-parser')
const app = new Koa();
app.use(parser());
app.use(static(__dirname + "/public"));
app.use(views(__dirname + '/views', {
map: { html: 'nunjucks' }
}));
let dataList = ["香蕉", "苹果", "鸭梨"];
//get查看
router.get("/fruits", ctx => {
ctx.body = dataList;
})
//post添加
router.post("/fruits", ctx => {
let fruit = ctx.request.body.fruit;
dataList.push(fruit);
ctx.body = dataList;
})
//put修改
router.put("/fruits/:id", ctx => {
let id = ctx.params.id;
let fruit = ctx.request.body.fruit;
dataList.splice(id, 1, fruit);
ctx.body = dataList;
})
//delete删除
router.delete("/fruits/:id", ctx => {
let id = ctx.params.id;
dataList.splice(id, 1);
ctx.body = dataList;
})
app.use(router.routes())
app.listen(3000, () => {
console.log("server is running");
})
index.html
基本用法
axios.get("/fruits").then(res => {
console.log(res.data);
})
axios.get返回值是一个promise对象 res是响应,若想要响应的数据,res.date 正经用法
<script>
// //axios.get返回值是一个promise对象
// axios.get("/fruits").then(res => {
// console.log(res.data);
// })
document.querySelector(".get").onclick = function () {
axios.get("/fruits").then(res => {
console.log(res.data);
})
}
document.querySelector(".post").onclick = function () {
axios.post("/fruits", {
fruit: "草莓"
}).then(res => {
console.log(res.data);
})
}
document.querySelector(".put").onclick = function () {
axios.put("/fruits/1", {
fruit: "西瓜"
}).then(res => {
console.log(res.data);
})
}
document.querySelector(".delete").onclick = function () {
axios.delete("/fruits/0").then(res => {
console.log(res.data)
})
}
</script>
通过上面的代码可以看到,使用Axios完成异步的数据操作是非常简单的
我们之前使用jQuery主要是用来操作DOM,其实jQuery也封装了Ajax方法,实例代码如下所示:
$(".get").click(function () {
$.ajax({
url: "/fruits",
type: "get"
}).done(res => {
console.log(res, "jquery的ajax方法")
})
})