02-Ajax入门
在某些项目中,我们只希望获取页面的局部数据,而不用整页刷新,这个时候就需要使用Ajax来实现功能了。
Ajax 的全称是Asynchronous JavaScript and XML(异步的JavaScript 和 XML),早些时候数据交互格式多为xml格式,例如:
<fruit>
<name>apple</name>
<weight>0.5kg</weight>
<color>red</color>
</fruit>
现在仍然存在很多xml交互数据,但是目前主流的数据格式使用的是json(JavaScript对象表示法),例如:
{
"fruit":{
"name":"apple",
"weight":"0.5kg",
"color":"red"
}
}
Ajax原理
之前的学习内容中,我们是通过以下方式向服务器发送请求的:
1. 在浏览器中直接输入网址
2. a标签实现的页面跳转
3. 表单提交
4. Postman模拟http请求
Ajax的原理是通过`XMLhttpRequest`对象向服务器发送请求,例如:
``` js
//后台程序
router.get("/", async ctx => {
await ctx.render("index")
})
router.get("/data", async ctx => {
ctx.body = "hello world"
})
```
``` js
//前端程序
let xhr = new XMLHttpRequest(); //创建XHR对象
xhr.open("get","/data"); // open() 第一个参数规定请求的类型,第二个参数写路径url
xhr.send() //发送请求
xhr.onreadystatechange = function(){ //监听readyState事件
// 0: 请求未初始化
// 1: 服务器连接已建立
// 2: 请求已接收
// 3: 请求处理中
// 4: 请求已完成,且响应已就绪
// status 状态码
if(xhr.readyState === 4 && xhr.status === 200){
alert(xhr.responseText) // 响应的文本
}
}
```
这里需要注意的是,上面的代码,我们在实际开发项目中并不常用,因为通常情况下,我们会引入第三方Ajax库来处理异步请求
封装一个Ajax方法
通过回调函数:
``` js
function myAjax(method,url,next) {
let xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.send()
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
next(xhr.responseText);
}
}
}
document.querySelector("button").onclick = function() {//调用封装的Ajax
myajax("get","/data",function(data){
alert(data);
});
}
```
过多的回到函数会使代码难以维护,因此建议使用promise对象来封装Ajax方法:
function myajax(method, url, next) {
return new Promise(function (resolve,reject) {
let xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.send(); //可以向后台传输数据
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
resolve(xhr.responseText);
}
}
reject("获取数据失败")
})
}
document.querySelector("button").onclick = async function () {
let p = myajax("get", "data");
p.then(function (data) {
alert(data);
})
}
then()方法可以写回调函数来获取数据