您的位置:首页 > Web前端 > Vue.js

vue结合axios与后端进行ajax交互的方法

2018-07-06 14:38 726 查看

以前vue官方推荐的ajax库是vue-resource, 现在改为axios

axios的github仓库

实现的效果:

异步请求

页面异步发出get请求获取数据,提交表单异步post数据到服务端

客户端

客户端代码

代码解析:

// 服务端请求地址
let url = 'http://local.php.com/index.php';
let vm = new Vue({
el: "#app",
data: {
list: [],
name: '',
saying: '',
},
methods: {
add() {
// 传送的数据为json格式
let data = JSON.stringify({
name: this.name,
saying: this.saying
});
axios.post(url, data)
.then(function (response) {
// console.log(response);
// 获取服务端返回的数据
vm.$data.list = response.data;
})
.catch(function (error) {
console.log(error);
});
}
}
});
axios.get(url, {})
.then(function (response) {
vm.$data.list = response.data;
})
.catch(function (error) {
console.log(error);
})
.then(function () {
// always executed
});

服务端

使用php作为服务端程序

服务端代码

代码解析:

<?php
header("Access-Control-Allow-Origin:*"); // 如果客户端和服务端不同域,要加上这行代码,不然会报跨域错误
$data = [
1 => ['name' => '孙悟空', 'saying' => '我是在地球上成长的赛亚人'],
];
$post = file_get_contents("php://input"); // 不要用$_POST接收数据
if ($post) {
$data[] = json_decode($post, true);
}
echo json_encode($data, true);

异步请求.gif

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  vue ajax axios