一、ajax,jQuery和axios的关系
ajax技术实现了网页的局部数据刷新,是原生的javascript
jQuery和axios都对ajax进行了封装
ajax是针对MVC(model,view,controller)进行编程
axios是针对MVVM(model,view,view model)进行编程
二、axios的简单实现
<body>
<div id="app">
<table>
<thead>
<th>索引</th>
<th>姓名</th>
<th>年龄</th>
</thead>
<tbody>
<!-- 第一个要是对象,第二个是索引 -->
<tr v-for="(user,index) in userList">
<td>{{index}}</td>
<td>{{user.name}}</td>
<td>{{user.age}}</td>
</tr>
</tbody>
</table>
</div>
<!-- 引入vue和axios的js文件 -->
<script src="./vue.min.js"></script>
<script src="./axios.min.js"></script>
<script>
new Vue({
el:'#app',
data:{
userList:[] //先定义一个空的数组,用来存取到的json数据
},
created(){
//在页面渲染前调用当前vue中的方法,得到返回json数据,就可以在把数据渲染到页面上了
this.getUserList();
},
methods:{
getUserList(){
//使用axios方式ajax请求
axios.get("user.json") //get方式请求,或post方式请求,里面传入请求的接口路径
.then( response => { //请求成功调用的方法,使用箭头函数,response是参数,箭头后面是返回结果
console.log(response) //response也是请求成功后获得的包含所有信息的json数据,其中有一个data就存的是user.json中的数据
this.userList=response.data.data.users; //用空数组来接收users的值
})
.catch( error => { //请求失败调用的方法
console.log(error)
})
}
}
})
</script>
</body>
//原生ajax
$.ajax({
url: 'http://jsonplaceholder.typicode.com/users',
type: 'get',
dataType: 'json',
data: {
},
success: function (response) {
console.log(response);
}
})