以前vue官方推荐的ajax库是vue-resource, 现在改为axios
实现的效果:
异步请求
页面异步发出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
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持鸟哥教程(niaoge.com)。
(章鱼喵_)
原文链接:https://www.jianshu.com/p/37ab77e5babe
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#niaoge.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。