以前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
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
© 版权声明
THE END
暂无评论内容