Vue中的AJAX请求vue-resource
首先需要引入vue-resource文件,但是在这之前一定要引入vue.js文件
<script src="vue2.5.17.js"></script> <script src="vue-resource.js"></script>
这样在加载的时候就会生成一个 $http ,可以利用它发送请求
GET请求
<html> <head> <title>test</title> <script src="vue2.5.17.js"></script> <script src="vue-resource.js"></script> </head> <div id="app"></div> <script> new Vue({ el: "#app", methods: { this.$http.get("http://127.0.0.1:8000/test/").then(function(resp){ let data = resp.body; console.log(data); console.log("这是返回方法"); }, function(resp){ console.log("这是错误处理方法"); }) } }); </script> </html>
POST请求
注意点:$http.post()方法中的第三个参数默认写成 {emulateJSON: true} ,否则可能造成服务器无法接受请求
$http.post()中有三个参数
- 参数一:要发送的url地址
- 参数二:传输的数据
- 参数三:{emulateJSON: true}
后面接上then用来定义返回成功执行的函数跟请求出错的函数
<html> <head> <title>test</title> <script src="vue2.5.17.js"></script> <script src="vue-resource.js"></script> </head> <div id="app"></div> <script> new Vue({ el: "#app", methods: { this.$http.post("http://127.0.0.1:8000/test/", {name: 'lions'}, {emulateJSON: true}).then(function(resp){ let data = resp.body; console.log(data); console.log("这是返回方法"); }, function(resp){ console.log("这是错误处理方法"); }) } }); </script> </html>
JSONP请求
jsonp请求用来解决ajax跨域请求问题,使用jsonp实现跨域首先要保证服务器api支持jsonp的请求格式
<html> <head> <title>test</title> <script src="vue2.5.17.js"></script> <script src="vue-resource.js"></script> </head> <div id="app"></div> <script> new Vue({ el: "#app", methods: { this.$http.jsonp("http://127.0.0.1:8000/test/").then(function(resp){ let data = resp.body; console.log(data); }, function(res) { alert(res.status); }) } }); </script> </html>