一、Ajax简介
以前,我们访问浏览器页面时,都是整页刷新的。
有时候,没有必要整页的数据都刷新,只需要一部分的数据刷新即可。
1、 Ajax全称
Ajax全称:Asynchronous JavaScript and XML(异步的JavaScript和XML)
2、 XML介绍
以前,异步交互的格式,都是用XML格式。
如:
<fruit>
<name>apple</name>
<weight>0.5kg</weight>
<color>red</color>
</fruit>
3、Json介绍
现在,主流的格式,是Json格式。
如:
{
"fruit" : {
"name" : "apple",
"weight" : "0.5kg",
"color" : "red"
}
}
4、Ajax优缺点
(1)优点:
按需获取数据,提升系统性能。
(2)缺点:
异步获取数据,不利于搜索引擎优化。
二、Ajax原理
1、思考:之前我们是如何向服务器发送请求的?
(1)在浏览器中直接输入网址
(2)a标签,实现页面跳转
(3)表单提交
(4)Postman模拟http请求
2、XMLhttpRequest对象
(1)基本介绍
server.js:
const Koa = require("koa");
const router = require("koa-router")();
const nunjucks = require("nunjucks");
const views = require("koa-views");
const parser = require("koa-parser");
const app = new Koa();
app.use(views(__dirname + "/views", {
map: {
html: "nunjucks"
}
}))
app.use(parser());
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:
<body>
<h1>首页</h1>
<button>获取数据</button>
<script>
document.querySelector("button").onclick = function () {
// 创建XMLHttpRequest对象
let xhr = new XMLHttpRequest();
// open可以用来规定请求的类型
xhr.open("get","/data");
// 发送请求
xhr.send();
}
</script>
</body>
效果:
点击按钮时,获取到了:xhr对象发送过来的数据。
(2) onreadystatechange
<body>
<h1>首页</h1>
<button>获取数据</button>
<script>
document.querySelector("button").onclick = function () {
// 创建XMLHttpRequest对象
let xhr = new XMLHttpRequest();
// open可以用来规定请求的类型
xhr.open("get", "/data");
// 发送请求
xhr.send();
// 该事件监听readyState的变化
xhr.onreadystatechange = function () {
// 0:请求未初始化
// 1:服务器连接已建立
// 2:请求已接收
// 3:请求处理中
// 4:请求已完成,且响应已就绪
if (xhr.readyState === 4 && xhr.status === 200) {
alert(xhr.responseText);
}
}
}
</script>
</body>
效果:点击按钮时,弹出hello world。
三、 使用回调方式,获取到xhr.responseText
使用return(同步)的话,没法获取异步的数据。
<body>
<h1>首页</h1>
<button>获取数据</button>
<script>
document.querySelector("button").onclick = function () {
// 使用回调,获取到res
myajax("get", "/data", function (res) {
alert(res);
});
}
// 自定义ajax
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);
}
}
return result;
}
</script>
</body>
但是,程序如果大量使用回调函数的话,就会变得难维护。
四、使用Promise对象,获取xhr.responseText
<body>
<h1>首页</h1>
<button>获取数据</button>
<script>
document.querySelector("button").onclick = function () {
// 使用回调,获取到res
myajax("get", "/data").then(res => {
console.log("jinlai")
alert(res);
});
}
// 自定义ajax
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);
}
}
})
}
</script>
</body>
五、总结
这样写太麻烦了,以后工作中,用ajax,都是用封装好的第三方库。
比如:jQuery等...