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

本篇文章主要介绍了vue结合axios与后端进行ajax交互的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

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

axios的github仓库

实现的效果:

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

异步请求

页面异步发出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);

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

异步请求.gif

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

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/4dd9656b1fe72db62bfb073c045f61f9.html