学习Vue(14)——使用vue-resource发送请求

介绍

vue-resource是vue.js的一款插件,通过XMLHttpRequest或JSONP发起请求并处理响应.

vue-resource是vue 1推荐使用的,而axios是vue 2.0 推荐使用的,其实两个都可以向后端发送请求,获取响应。

安装

由于vue-resource.js是vue的一段插件,所以需要安装。

安装到本地请参考:https://blog.csdn.net/cnds123321/article/details/103988468

也可以使用CDN,引入:

<script src="https://cdn.staticfile.org/vue-resource/1.5.1/vue-resource.min.js"></script>

语法

在一个Vue实例中使用vue-resource,需要使用$http。

语法如下:

// 基于全局Vue对象使用http
Vue.http.get('/someUrl', [options]).then(successCallback, errorCallback);
Vue.http.post('/someUrl', [body], [options]).then(successCallback, errorCallback);

// 在一个Vue实例内使用$http
this.$http.get('/someUrl', [options]).then(successCallback, errorCallback);
this.$http.post('/someUrl', [body], [options]).then(successCallback, errorCallback);

在发送请求后,使用then方法来处理响应结果,then方法有两个参数,第一个参数是响应成功时返回的回调函数,第二个参数是响应失败时的回调函数。

回调函数的具体写法:

this.$http.get("/url",[options]).then(function(response){
    // 响应成功回调函数
},function(response){
	// 响应失败回调函数
});

GET请求

下面是使用的Java作为后端语言,使用servlet响应前台请求。

在这里需要传递参数,使用

this.$http.get("url", {
	params: {
		parm1: value1,
		parm2: value2
			}
}).then(function(res) {
	document.write(res.body);
}, function(res) {
	console.log(res.status);
});

index.html

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <title>Vue学习</title>
    <!-- 引入vue.js -->
    <script src="js/vue.min.js"></script>
    <!--引入vue-resource.js插件-->
    <script src="js/vue-resource.min.js"></script>
    <!-- 使用CDN引入Vue.js -->
    <!--<script type="text/javascript" src=" https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.8/vue.min.js"></script>-->
    <!-- 使用CDN引入vue-resource.js -->
    <!--<script type="text/javascript" src="https://cdn.staticfile.org/vue-resource/1.5.1/vue-resource.min.js"></script>-->
</head>
<body>
<div id="app">
    <p>登录成功用户(用户名:admin;密码:admin)</p>
    用户名:<input type="text" v-model="user"><br>
    密码:<input type="password" v-model="password"><br>
    <input type="button" value="登录" @click="login()">
</div>
<script>
    new Vue({
        el: '#app',
        data: {
            user: '',
            password: ''
        },
        methods: {
            login: function () {
                this.$http.get('http://localhost:8080/loginServlet', {
                    params: {
                        user: this.user,
                        password: this.password
                    }
                }).then(function (res) {
                    if (res.data.ok != 1) {
                        alert(res.data.msg);
                    } else {
                        alert(res.data.msg);
                    }
                }, function (res) {
                    console.log('传输失败');
                });
            }
        }
    })
</script>
</body>
</html>

浏览器展示:

用谷歌浏览器查看

响应为:

POST请求

post 发送数据到后端,需要第三个参数 {emulateJSON:true}。

emulateJSON 的作用: 如果Web服务器无法处理编码为 application/json 的请求,你可以启用 emulateJSON 选项。

发送POST请求的语法:

                // 发送POST请求
                this.$http.post(
                    'url',
                    data,
                    {emulateJSON: true}
                ).then(function (res) {
                    // 响应成功的回调函数
                }, function (res) {
                    // 响应失败的回调函数
                });

index.html

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <title>Vue学习</title>
    <!-- 引入vue.js -->
    <script src="js/vue.min.js"></script>
    <!--引入vue-resource.js插件-->
    <script src="js/vue-resource.min.js"></script>
    <!-- 使用CDN引入Vue.js -->
    <!--<script type="text/javascript" src=" https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.8/vue.min.js"></script>-->
    <!-- 使用CDN引入vue-resource.js -->
    <!--<script type="text/javascript" src="https://cdn.staticfile.org/vue-resource/1.5.1/vue-resource.min.js"></script>-->
</head>
<body>
<div id="app">
    <p>登录成功用户(用户名:admin;密码:admin)</p>
    用户名:<input type="text" v-model="user"><br>
    密码:<input type="password" v-model="password"><br>
    <input type="button" value="登录" @click="login()">
</div>
<script>
    new Vue({
        el: '#app',
        data: {
            user: '',
            password: ''
        },
        methods: {
            login: function () {
                // 发送POST请求
                this.$http.post('http://localhost:8080/loginServlet',
                    {
                        user: this.user,
                        password: this.password
                    },
                    {emulateJSON: true}
                ).then(function (res) {
                    if (res.data.ok != 1) {
                        alert(res.data.msg);
                    } else {
                        alert(res.data.msg);
                    }
                }, function (res) {
                    console.log('传输失败');
                });
            }
        }
    })
</script>
</body>
</html>

浏览器提交:

查看浏览器请求:

响应数据:

API

以使用全局对象方式 Vue.http 或者在一个 Vue 实例的内部使用 this.$http来发起 HTTP 请求。

// 基于全局Vue对象使用http
Vue.http.get('/someUrl', [options]).then(successCallback, errorCallback);
Vue.http.post('/someUrl', [body], [options]).then(successCallback, errorCallback);

// 在一个Vue实例内使用$http
this.$http.get('/someUrl', [options]).then(successCallback, errorCallback);
this.$http.post('/someUrl', [body], [options]).then(successCallback, errorCallback);

vue-resource 提供了 7 种请求 API(REST 风格):

get(url, [options])
head(url, [options])
delete(url, [options])
jsonp(url, [options])
post(url, [body], [options])
put(url, [body], [options])
patch(url, [body], [options])

除了 jsonp 以外,另外 6 种的 API 名称是标准的 HTTP 方法。

options 参数说明:

参数 类型 描述
url string 请求的目标URL
body ObjectFormDatastring 作为请求体发送的数据
headers Object 作为请求头部发送的头部对象
params Object 作为URL参数的参数对象
method string HTTP方法 (例如GET,POST,...)
timeout number 请求超时(单位:毫秒) (0表示永不超时)
before function(request) 在请求发送之前修改请求的回调函数
progress function(event) 用于处理上传进度的回调函数 ProgressEvent
credentials boolean 是否需要出示用于跨站点请求的凭据
emulateHTTP boolean 是否需要通过设置X-HTTP-Method-Override头部并且以传统POST方式发送PUT,PATCH和DELETE请求。
emulateJSON boolean 设置请求体的类型为application/x-www-form-urlencoded

通过如下属性和方法处理一个请求获取到的响应对象:

属性 类型 描述
url string 响应的 URL 源
body ObjectBlobstring 响应体数据
headers Header 请求头部对象
ok boolean 当 HTTP 响应码为 200 到 299 之间的数值时该值为 true
status number HTTP 响应码
statusText string HTTP 响应状态
方法 类型 描述
text() 约定值 以字符串方式返回响应体
json() 约定值 以格式化后的 json 对象方式返回响应体
blob() 约定值 以二进制 Blob 对象方式返回响应体

完整代码

项目结构:

如果对完整源码有兴趣。

可搜索微信公众号【Java实例程序】或者扫描下方二维码关注公众号获取更多。

注意:在公众号后台回复【CSDN202001181642】可获取本节源码。

发布了394 篇原创文章 · 获赞 41 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/cnds123321/article/details/104030944
今日推荐