Ajax第三方模块
事实上我们可以直接使用成熟的Ajax第三方模块,而不必“重新造轮子”
下载并引入Axios
npm install axios
用法
axios.method(url).then( res => {
console.log(res.data);
})
method可以是(get\post\put\delete…)
由于
axios.method(url)
返回的是一个Promise对象,所以用then来获取数据
示例
后端代码
const Koa = require('koa');
const router = require('koa-router')();
const views = require("koa-views");
const nunjucks = require("nunjucks");
const static = require("koa-static")
const parser = require("koa-parser")
const app = new Koa();
app.use(views(__dirname+"/views",{
map:{
html:"nunjucks"}
}));
app.use(static(__dirname+'/public'))
app.use(parser());
router.get('/',async (ctx)=>{
await ctx.render("axios");
})
let dataList = ["apple ","banana ","orange "];
router.get('/fruits', ctx =>{
ctx.body = dataList;
})
router.post("/fruits",ctx =>{
let fruit = ctx.request.body.fruit;
dataList.push(fruit);
ctx.body = dataList;
})
router.put("/fruits/:id",ctx => {
let id = ctx.params.id;
let fruit = ctx.request.body.fruit;
dataList.splice(id,1,fruit);//将第i+1个数据变成fruit 1是指项目数量
ctx.body = dataList;
})
router.delete("/fruits/:id",ctx=>{
let id = ctx.params.id;
dataList.splice(id,1);
ctx.body = dataList;
})
// router.get('/data',async ctx=>{
// ctx.body = "Data From Backend"
// })
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>test axios</title>
<link rel="stylesheet" href="/css/bootstrap-3.3.7-dist/css/bootstrap.css">
</head>
<body>
<div class="container">
<button class="get btn btn-success">查询数据</button>
<button class="post btn btn-success">添加数据</button>
<button class="put btn btn-success">修改数据</button>
<button class="delete btn btn-success">删除数据</button>
<p class="lead"><span id="output">后台的数据在这里显示</span></p>
</div>
<script src="/js/axios.min.js"></script>
<script src="/js/jquery-3.5.1.js"></script>
<script>
//查询数据
$(".get").on('click',function(){
//get方法放回一个Promise对象
axios.get('/fruits').then(res => {
$("#output").html(res.data);
})
})
//添加数据,post 需要传参
$(".post").on('click',function(){
axios.post('/fruits',{
fruit:"peach "
}).then(res => {
$("#output").html(res.data);
})
})
//修改数据,put 需要传参
$(".put").on('click',function(){
axios.put('/fruits/1',{
fruit:"watermelon "
}).then(res => {
$("#output").html(res.data);
})
})
//删除数据
$(".delete").on('click',function(){
axios.delete('/fruits/0').then(res => {
$("#output").html(res.data);
})
})
</script>
</body>
</html>
演示效果
jQuery自带的Ajax
用法
//jquery中的ajax方法
$.ajax({
url:"/fruits",
type:"get"
}).done(res => {
console.log(res);
})