Ajax
1.概念
定义:
AJAX :Asynchronous JavaScript And XML,异步的 JavaScript 和 XML。
作用:
- 与服务器进行数据交换:通过AJAX可以给服务器发送请求,服务器将数据直接响应回给浏览器。
- 异步交互:可以在不重新加载整个页面的情况下,与服务器交换数据并更新部分网页的技术,如:搜索联想、用户名是否可用校验,等等。
2.异步与同步
同步发送请求: 浏览器页面在发送请求给服务器,在服务器处理请求的过程中,浏览器页面不能做其他的操作。只能等到服务器响应结束后浏览器页面才能继续做其他的操作。
异步发送请求: 浏览器页面发送请求给服务器,在服务器处理请求的过程中,浏览器页面还可以做其他的操作。
3.原生代码(了解)
<!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>原生Ajax</title>
</head>
<body>
<input type="button" value="获取数据" onclick="getData()">
</body>
<script>
function getData(){
//1. 创建XMLHttpRequest
var xmlHttpRequest = new XMLHttpRequest();
//2. 发送异步请求
xmlHttpRequest.open('GET','http://yapi.smart-xwork.cn/mock/169327/emp/list');
xmlHttpRequest.send();//发送请求
//3. 获取服务响应数据
xmlHttpRequest.onreadystatechange = function(){
if(xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200){
alert(xmlHttpRequest.responseText);
}
}
}
</script>
</html>
原生Ajax获取返回的结果是json格式的字符串文本,要想解析,需要手动调用JSON.parse()转为js对象。
4.Axios
① 引入 axios 的 js 文件
<script src="js/axios-0.18.0.js"></script>
②使用axios发送请求,并获取响应结果
<!-- 发送 get 请求 -->
axios({
method:"get",
url:"http://yapi.eehp.cn/mock/47/web/day02/emp/list"
}).then((result) => {
console.log(result.data);
});
<!-- 发送 post 请求 -->
axios({
method:"post",
url:"http://yapi.lkweixin.com/mock/6377/emp/deleteById",
data:"id=1"
}).then((result) => {
console.log(result.data);
});
简化写法
<script src="js/axios-0.18.0.js"></script>
<script>
//发送Ajax请求 - GET
axios.get("http://yapi.eehp.cn/mock/47/web/day02/emp/list").then((result) => {
console.log(result);
})
//发送Ajax请求 - POST
axios.post("http://yapi.eehp.cn/mock/47/web/day02/emp/deleteById","id=1").then((result) => {
console.log(result);
})
</script>
5.案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="box" id="box">
<table border="1" cellspacing="0" width="100%">
<tr>
<th>编号</th>
<th>姓名</th>
<th>图像</th>
<th>性别</th>
<th>职位</th>
<th>入职日期</th>
<th>最后操作时间</th>
</tr>
<tr align="center" v-for="(code,index) in codes">
<td>{{index + 1}}</td>
<td>{{code.name}}</td>
<td><img width="60px" :src="code.image" alt=""></td>
<td>{{code.gender == 1 ? "男" : "女"}}</td>
<td>{{code.job}}</td>
<td>{{code.entrydate}}</td>
<td>{{code.updatetime}}</td>
</tr>
</table>
</div>
</body>
<script src="js/vue.js"></script>
<script src="js/axios-0.18.0.js"></script>
<script>
new Vue({
el: "#box",
data: {
codes: []
},
mounted(){
axios.get("http://yapi.eehp.cn/mock/47/web/day02/emp/list").then((result) => {
// console.log(result.data);
this.codes = result.data.data
});
}
})
</script>
</html>