vue $http请求服务

来源:互联网 发布:笔记本支架哪个好 知乎 编辑:程序博客网 时间:2024/06/05 04:06

vue中的$http服务  需要引入一个叫vue-resource.js的文件,因为vue.js中没有$http服务。如果需要使用这个服务去百度下载vue-resource.js

第一种get方法

<!DOCTYPE html><html><head><meta charset="UTF-8"><title></title><script src="js/vue.js"></script><script src="js/vue-resource.js"></script></head><body><div id="app"><input type="button" value="点击获取" @click="get()"/></div><script>new Vue({el:"#app",methods:{get:function(){this.$http.get('get.php',{a:10,b:1}).then(function(res){alert(res.data);},function(res){alert(res.status)});}}})</script></body></html>

get.php文件:

<?php
$a=$_GET['a'];
$b=$_GET['b'];
echo $a-$b;
?>

get方法有两个参数get("PHP文件",“参数”)


post方法:

<!DOCTYPE html><html><head><meta charset="UTF-8"><title></title><script src="js/vue.js"></script><script src="js/vue-resource.js"></script></head><body><div id="app"><input type="button" value="点击获取" @click="get()"/></div><script>new Vue({el:"#app",methods:{get:function(){this.$http.post('post.php',{a:2,b:3},{emulateJSON:true}).then(function(res){alert(res.data);},function(res){alert(res.status)});}}})</script></body></html>
post.php:

<?php
$a=$_POST['a'];
$b=$_POST['b'];
echo $a+$b;
?>

post方法有三个参数post("php文件","参数","emulateJSON:true")

emulateJSON:true  模拟一个JSON数据发送到服务器,这样才可以成功运行



这样放在服务器环境下就可以运行了,我用的是phpstudy



原创粉丝点击