首页/前端工程师外包/ vue与后端数据交互(ajax):vue-resource

vue与后端数据交互(ajax):vue-resource

发布-xiaoming | 浏览量-

 必须引入一个库:vue-resource

1.获取普通文本数据 
比如:a.txt:
 
welcomet to vue!!!
 
<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8">
    <script src="http://unpkg.com/vue/dist/vue.js"></script>
    <script src="https://cdn.jsdelivr.net/vue.resource/1.0.3/vue-resource.min.js"></script>
    <script type="text/javascript">
        window.onload = function(){
            var vm = new Vue({
                el:'#box',
                data:{
                    msg:'Hello World!',
                },
                methods:{
                    get:function(){
                        //发送get请求
                        this.$http.get('a.txt').then(function(res){
                            alert(res.body);    
                        },function(){
                            console.log('请求失败处理');
                        });
                    }
                }
            });
        }
    </script>
</head>
<body> 
    <div id="box">
        <input type="button" @click="get()" value="按钮">
    </div>
</body>
</html>
 
上面代码实现了,点击按钮,就发送get请求,然后把拿到的数据alert出来。 
这里写图片描述
 
2.get发送数据给后端 
假设后端地址是get.php,代码如下:
 
this.$http.get('get.php',{params:{a:1,b:2}}).then(function(res){
    alert(res.body);    
},function(res){
    console.log(res.status);
});
 
this.$http.get('get.php',jsonData) 第二个参数就是传到后端的数据。
 
3.post请求 
post发送数据到后端,还需要第三个参数:{emulateJSON:true}
this.$http.post('post.php',{params:{a:1,b:2}}},{emulateJSON:true}).then(function(res){
    alert(res.body);    
},function(res){
    console.log(res.status);
});
 
4.jsonp 
这是360搜索jsonp的接口: 
https://sug.so.360.cn/suggest?callback=suggest_so&word=a 
这里写图片描述
我们看vue-resource如何使用jsonp
 
this.$http.jsonp('https://sug.so.360.cn/suggest',{word:'a'},{jsonp:'callback'}).then(function(res){
    console.log(res.data);
},function(res){
    console.log(res.status);
});

 

原文地址:http://www.35ui.cn/post/20171022902.html

标签vueajaxvue-resource

上一条: 前端优化:js优化if else
下一条: rel=”nofollow” rel nofollow 怎么用

或许你还对下面的文章感兴趣