Ajax入门
概述
Ajax原理
server.js
const Koa = require("koa");
const router = require("koa-router")();
const views = require("koa-views");
const nunjucks = require("nunjucks");
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");
});
index.html
<!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>获取的数据</button>
<script>
document.querySelector("button").onclick = function(){
let xhr = new XMLHttpRequest();
xhr.open("get","/data");//规定请求的类型,路径
xhr.send();//发送请求
xhr.onreadystatechange = function(){//监听xhr的readystate属性,readystate变化了就会触发事件
if(xhr.readyState === 4 && xhr.status == 200){
alert(xhr.responseText);//发出请求后的响应文本
}
}
}
</script>
</body>
</html>
readyState的数值
这么多代码仅仅只获取了一个字符串,显得繁琐。以后的项目开发中更多的是用封装好的第三方库用ajax,不必写这些,会看就行
封装上述的ajax
获取异步数据不能用return,因为异步数据往往需要从网络中花费些时间加载出来,而return会立即执行,导致数据加载不出来
可以看到没有获取到数据
但请求发送了服务器也响应了
通过回调函数实现封装ajax
index.html
<!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>获取的数据</button>
<script>
document.querySelector("button").onclick = function(){
myajax("get","/data",function(res){//res对应xhr.responseText
alert(res);
});
}
function myajax(method,url,next){//next回调函数
let xhr = new XMLHttpRequest();
xhr.open(method,url);
xhr.send();
let rusult = "";
xhr.onreadystatechange = function(){
if(xhr.readyState === 4 && xhr.status == 200){
next(xhr.responseText);
}
}
}
</script>
</body>
</html>
通过Promise实现封装ajax
但回调函数用多了不利于维护,现在更常用promise
<!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>获取的数据</button>
<script>
document.querySelector("button").onclick = function(){
//myajax会return一个Promise对象
//then获取resolve方法传进来的值xhr.responseText
myajax("get","/data").then(res => {//res回调
alert(res);
});
}
function myajax(method,url){
return new Promise(function(resolve){
let xhr = new XMLHttpRequest();
xhr.open(method,url);
xhr.send();
let rusult = "";
xhr.onreadystatechange = function(){
if(xhr.readyState === 4 && xhr.status == 200){
resolve(xhr.responseText);
}
}
});
}
</script>
</body>
</html>