吉福美食网
您的当前位置:首页vue结合axios与后端进行ajax交互的方法

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

来源:吉福美食网


以前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

显示全文