vue-resource 与服务器端通信及跨域实际应用

简介:

与服务器端通信


Vue.js 可以构建一个完全不依赖后端服务的应用,同时也可以与服务端进行数据交互来同步界面的动态更新。Vue 本身并没有提供与服务端通信的接口,但是通过插件的形式实现了基于AJAX、JSONP 等技术的服务端通信。


vue-resource 是一个通过 XMLHttpRequest 或 JSONP 技术实现异步加载服务端数据的 Vue 插件,该插件提供了一般的 HTTP 请求接口和 RESTful 架构请求接口,并且提供了全局方法和 Vue 组件实例方法。


一般的 HTTP 请求接口按照调用的便捷程度又分为底层方法 和 便捷方法,便捷方法是对底层方法的封装。在 vue-resource 中我们可以全局配置,同时,它提供了数据获取各个阶段的钩子,使得我们可以对数据获取过程进行更好的控制。


vue-resource 插件提供的公开方法总览图:

wKiom1hA4cCS6KzJAADliGEoFZ0327.png

vue-resource 安装及配置


1、安装  

vue-resource 提供了 npm、bower、手动编译等安装方式,可以根据业务需要选择其中一种方式进行安装。


1-1、npm

如果项目基于 npm 包方式来开发,则可以使用 npm 来按照 vue 和 vue-resource,执行如下命令

$ npm i vue vue-resource --save-dev


wKiom1hA41aCGyivAAAMJQSd5Eg489.png


然后在项目中引入 Vue.js 和 vue-resource,并且在 Vue.js 中注册 vue-resource 插件,代码如下:

// 引入 Vue.js 和 vue-resource

var Vue = require('vue');

var VueResource = require('vue-resource');

// 注册 vue-resource 插件

// 注意,假如 Vue.js 已经在html 中直接引入,则不需要再执行此步骤

// 此时 vue-resource 会自动调用 Vue.use 方法来注册

Vue.use(VueResource);


1-2、bower

当业务代码使用 bower 来管理时,可以使用 bower 安装到指定目录。假如该目录为 js/vendor,执行如下命令:

$ bower install vue-resource


在 HTML 中,在 vue 文件之后引入 vue-resource,代码如下:

<!-- 引入 Vue-->

<script src="js/vendor/vue.js"></script>



<!-- 引入 vue-resource -->

<script src="js/vendor/vue-resource.js"></script>


1-3、手动编译

当想尝试一些 Vue 中并未发布的新特性时,可以直接 clone 源码,手动构建实现。由于在未正式发布之前,有些特性可能被移除,所以不建议在生产环境中使用手动编译方式安装。


没有安装 git 工具的,可参照百度提供的步骤并解决安装过程中遇到的相关问题

http://jingyan.baidu.com/article/d2b1d1029065ba5c7e37d43e.html?st=2&os=0&bd_page_type=1&net_type=


执行命令如下:

$ git clone https://github.com/pagekit/vue-resource


$ cd vue-resource


$ npm install


$ npm run build


wKioL1hA6rzxDB83AAAfM1uhkVs247.png

wKioL1hBL0Kx2bxZAABOQ0RI548752.png


在C盘对应的目录下就生成了一系列的 vue-resource 文件


wKioL1hBL4DRr5McAABMncpFUrI254.png


2、参数配置


vue-resource 将请求配置分为全局配置、组件实例配置和调用配置 三部分,这三部分的优先级依次增高,优先级高的配置会覆盖优先级低的配置。


全局配置默认参数,如图:

wKioL1hA8JaAjSISAABhLjSBbXs404.png


2-1、全局配置

1
2
Vue.http.options.root =  '/root' ;
Vue.http.headers.common[ 'Authorization' ] =  'Basic YXBpOnBhc3N3b3Jk' ;


2-2、组件实例配置

在实例化组件时,可以传入 http 选项来进行配置

1
2
3
4
5
6
7
8
new  Vue({
     http: {
         root:  '/root' ,
         headers: {
             Authorization:  'Basic YXBpOnBhc3N3b3Jk'
         }
     }
})


2-3、方法调用时配置

在调用 vue-resource 请求方法时传入选项对象

1
2
3
4
5
6
7
8
9
10
11
12
new  Vue({
     ready: function (){
         //get请求
         this .$http.get({url: '/someUrl' , headers:{Authorization:  'Basic YXBpOnBhc3N3b3Jk' }})
                   .then( function (successResponse){
                         //请求成功的回调函数
                         }, function (errorResponse){
                         //请求失败的回调函数
                         }
                   )
     }
})



3、headers 配置

headers 属性用来配置请求头。合并策略遵循参数配置合并策略。除了参数配置 headers 属性可以设置请求头外,在 vue-resources 中也提供了全局默认的 headers 配置

wKioL1hBArHTQuVgAACBBadjvJA751.png上图中,可以看到 Vue.http.headers 键值可以是 HTTP 方法名、common、custom 三种类型。这三种类型的配置会进行合并,优先级从低到高依次是 common、custom、HTTP方法名。


其中 common 对应的请求头会在所有请求头中设置,custom 对应的请求头在非跨域时设置,HTTP 方法名对应的请求头只有在请求的 method 匹配方法名时才会被设置。



4、基本 HTTP 调用

基本 HTTP 调用即普通的 GET、POST 等基本的 HTTP 操作,实际上执行增、删、改、查是前后端开发人员共同约定的,并非通过 HTTP 的请求方法如 GET 代表获取数据、PUT代表写入数据、POST 代表更新数据。


4-1、底层方法

全局的 Vue.http 方法和Vue 组件的实例方法 this.$http 都属于底层方法,它们根据所传 option 参数的 method 属性来判断请求方式是 GET 还是 POST,或者是其它合法的 HTTP 方法


(1)、全局调用          this -> window

1
2
3
// global Vue object
Vue.http.get( '/someUrl' , [options]).then(successCallback, errorCallback);
Vue.http.post( '/someUrl' , [body], [options]).then(successCallback, errorCallback);


(2)、组件实例调用        this -> Vue 实例

1
2
3
// in a Vue instance
this .$http.get( '/someUrl' , [options]).then(successCallback, errorCallback);
this .$http.post( '/someUrl' , [body], [options]).then(successCallback, errorCallback);


以组件实例调用方式为例来了解一下如何发送 POST 请求,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
new  Vue({
     ready: function (){
         //POST 请求
         this .$http({
             url: '/book' ,
             method: 'POST' ,
             //请求体中发送的数据
             data:{
                 cat: '1'
             },
             //设置请求头
             headers:{
                 'Content-Type' : 'x-www-form-urlencoded'
             }
         }).then(
                 function (response){
                     //请求成功回调
                 },
                 function (response){
                     //请求失败回调
                 }
         )
     }
})


示例一:

HTML代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<!DOCTYPE html>
< html >
< head  lang = "en" >
     < meta  charset = "UTF-8" >
     < meta  http-equiv = "X-UA-Compatible"  content = "IE=edge" >
     < meta  name = "viewport"  content = "width=device-width, initial-scale=1" >
     < link  href = "//cdn.bootcss.com/bootstrap/3.0.1/css/bootstrap.css"  rel = "stylesheet" >
     < title ></ title >
</ head >
< body >
< div  id = "app" >
     < input  class = "btn btn-success"  type = "button"  value = "按钮"  @ click = "get()" >
</ div >
 
< script  src = "//cdn.bootcss.com/vue/2.0.8/vue.js" ></ script >
< script  src = "//cdn.bootcss.com/vue-resource/0.7.2/vue-resource.js" ></ script >
< script >
     new Vue({
         el:'#app',
         data:{
 
         },
         methods:{
             get:function(){
                 this.$http.get('aa.txt').then(function(res){
                     alert(res.data);
                 },function(res){
                     alert(res.status);
                 });
             }
         }
     });
</ script >
</ body >
</ html >


在同级目录下,新建一个“aa.txt”,并写上一段文本“welcome vue-----”,用Apche服务器打开网页,点击按钮以后

wKiom1hBLWCyzI_wAAA-36C2mFw415.png

成功请求到了 aa.txt,并拿到了响应数据。如果响应失败,就会弹出响应失败的状态码 status,比如把 aa.txt 改成 bb.txt,就会报404 错误

wKiom1hBLhThxybiAABcjRIXl44682.png




示例二:

HTML代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<!DOCTYPE html>
<html>
<head lang= "en" >
     <meta charset= "UTF-8" >
     <meta http-equiv= "X-UA-Compatible"  content= "IE=edge" >
     <meta name= "viewport"  content= "width=device-width, initial-scale=1" >
     <link href= "//cdn.bootcss.com/bootstrap/3.0.1/css/bootstrap.css"  rel= "stylesheet" >
     <title></title>
</head>
<body>
<div id= "app" >
     <input class= "btn btn-success"  type= "button"  value= "按钮"  @click= "get()" >
</div>
 
<script src= "//cdn.bootcss.com/vue/2.0.8/vue.js" ></script>
<script src= "//cdn.bootcss.com/vue-resource/0.7.2/vue-resource.js" ></script>
<script>
     new  Vue({
         el: '#app' ,
         data:{
 
         },
         methods:{
             get: function (){
                 this .$http.get( 'get.php' ,{
                     a:1,
                     b:2
                 }).then(
                     function (response){  //成功的回调函数
                         alert(response.data);
                     },
                     function (response){  //失败的回调函数
                         alert(response.status);
                     }
                 )
             }
         }
     });
</script>
</body>
</html>


PHP代码:

1
2
3
4
5
<?php
$a = $_GET [ 'a' ];
$b = $_GET [ 'b' ];
echo  $a + $b ;
?>


点击按钮以后,发起一个 get 请求,如果请求成功则返回 a+b的结果,如果请求失败则返回对应的状态码

wKiom1hBMvHgBJgnAABVqL_YuOk895.png


4-2、便捷方法

不同于底层方法,便捷方法是对底层方法的封装,在调用时可以省去配置选项 option 中的method 属性。以下是 vue-resource 提供的便捷方法列表:


  • get(url, [options])

  • head(url, [options])

  • delete(url, [options])

  • jsonp(url, [options])

  • post(url, [body], [options])

  • put(url, [body], [options])

  • patch(url, [body], [options])


options 参数列表

参数
类型 描述
url
string 请求的 URL 地址
body Object, FormData, string 请求体
headers Object HTTP请求头部
params Object

URL参数,默认值为{}

Vue.http({

 url:'http://example.com/{book}',

 params:{

  book:'vue',

  cat:'1'

 }

})

最终URL为 http://example.com/vue?cat=1

method
string 请求的HTTP方法(GET、POST等),默认GET
timeout number 请求超时时间,默认值为0,单位是ms,0表示没有超时限制,超时后将会取消当前请求
before
function(request) 请求发送前的处理函数。默认值为null,接受请求选项对象作为参数
progress function(event) 处理ProgressEvent的回调函数
credentials boolean
表示跨域请求时是否需要使用凭证
emulateHTTP boolean 默认值为false,当值为true时,用HTTP的POST方法发送PUT、PATCH、DELETE等请求,并设置请求头字段 HTTP-Method-Override为原始请求方法
emulateJSON boolean 默认值为false,当值为true并且data为对象时,设置请求头Content-Type的值为 application/x-www-form-urlencoded
xhr Object 默认值为null,该对象中的属性都会应用到原生xhr实例对象上
upload Object 默认值为null,该对象的属性都会应用到原生xhr实例对象的upload属性上
jsonp string

默认值为callback,JSONP请求中回调函数的名

Vue.http({

 url:'http://example.com/book',

 method:'JSONP',

 jsonp:'cb'

})

crossOrigin Object 默认值为null,表示是否跨域,如果没有设置该属性,vue-resource 内部会判断浏览器当前 URL 和请求 URL 是否跨域


示例代码:

HTML代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<!DOCTYPE html>
< html >
< head  lang = "en" >
     < meta  charset = "UTF-8" >
     < meta  http-equiv = "X-UA-Compatible"  content = "IE=edge" >
     < meta  name = "viewport"  content = "width=device-width, initial-scale=1" >
     < link  href = "//cdn.bootcss.com/bootstrap/3.0.1/css/bootstrap.css"  rel = "stylesheet" >
     < title ></ title >
</ head >
< body >
< div  id = "app" >
     < input  class = "btn btn-success"  type = "button"  value = "按钮"  @ click = "get()" >
</ div >
 
< script  src = "//cdn.bootcss.com/vue/2.0.8/vue.js" ></ script >
< script  src = "//cdn.bootcss.com/vue-resource/0.7.2/vue-resource.js" ></ script >
< script >
     new Vue({
         el:'#app',
         data:{
 
         },
         methods:{
             get:function(){
                 this.$http.post('post.php',{
                     a:1,
                     b:20
                 },{
                     emulateJSON:true
                 }).then(
                         function(response){ //成功的回调函数
                             alert(response.data);
                         },
                         function(response){ //失败的回调函数
                             alert(response.status);
                         }
                 )
             }
         }
     });
</ script >
</ body >
</ html >


PHP代码:

1
2
3
4
5
<?php
$a = $_POST [ 'a' ];
$b = $_POST [ 'b' ];
echo  $a - $b ;
?>


把 emulateJSON的值改为 true,运行代码

wKiom1hBNY3gBYBsAAA7HuRq_hA372.png

把 emulateJSON的值改为默认值false 或者去掉“{emulateJSON:true}”,运行代码,报错了

wKiom1hBNfqjem8rAABmX-SFnOQ386.png



5、response 对象

response 对象包含服务端返回的数据,以及 HTTP 响应状态、响应头等信息。

属性
类型 描述
url
string 响应的 URL
body Object, Blob, string 响应体数据
headers Header 响应头对象
ok boolean HTTP 状态码(200-299之间)
status number HTTP 响应状态码
statusText string HTTP 响应文本
data Object,string 服务器端返回的数据,已使用JSON.parse解析
方法 类型 描述
text( ) Promise 把响应数据解析为字符串
json( ) Promise 把响应数据解析为JSON对象
blob( ) Promise 把响应数据解析为二进制对象


示例代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{   // POST /someUrl
   this .$http.post( '/someUrl' , {foo:  'bar' }).then((response) => {    
     // get status
     response.status;    
     // get status text
     response.statusText;    
     // get 'Expires' header
     response.headers.get( 'Expires' );    
     // set data on vm
     this .$set( 'someData' , response.body);
 
   }, (response) => {    
   // error callback
   });
}


从响应对象中获得一个 image并使用blob() 方法提取image的数据内容

1
2
3
4
5
6
7
8
9
10
11
{
     // GET /image.jpg
     this .$http.get( '/image.jpg' ).then((response) => {
 
         // resolve to Blob
         return  response.blob();
 
}).then(blob) => {
     // use image Blob
});
}



6、拦截器(Interceptors)

可以全局进行拦截设置,拦截器可以在请求发送前或响应返回时做一些特殊的处理


6-1、处理请求消息

1
2
3
4
5
6
7
8
Vue.http.interceptors.push((request, next) => {
 
     // modify request
     request.method =  'POST' ;
 
// continue to next interceptor
next();
});



6-2、处理请求和响应消息

1
2
3
4
5
6
7
8
9
10
11
12
Vue.http.interceptors.push((request, next)  => {  
 
   // modify request
   request.method =  'POST' ;  
   
   // continue to next interceptor
   next((response) => {    
    // modify response
     response.body =  '...' ;
 
   });
});



6-3、返回一个响应消息并停止处理

1
2
3
4
5
6
7
8
9
10
Vue.http.interceptors.push((request, next) => {
 
     // modify request ...
 
     // stop and return response
     next(request.respondWith(body, {
     status: 404,
     statusText:  'Not found'
     }));
});



7、跨域 AJAX


很多人认为 AJAX 只能在同域的情况下发送成功,很早的时候,由于浏览器安全策略,AJAX确实只能在同域的情况下发送。但是目前很多浏览器已经开始支持 XMLHttpRequest2,XMLHttpRequest2引入了大量的新特性,例如跨域资源请求(CORS)、上传进度事件、支持二进制数据上传/下载等。


这里初步了解下 vue-resource 中用到的 CORS 特性,以及 XMLHttpRequest2 的替代品 XDomainRequest


7-1、XMLHttpRequest2 CORS

XMLHttpRequest2 是第二代 XMLHttpRequest 技术,提交 AJAX请求还是和普通的 XMLHttpRequest 请求一样,只是增加了一些新特性。


在提交AJAX 跨域请求时,首先我们需要知道当前浏览器是否支持 XHR2,判断方法是使用 in 操作符检测当前 XHR实例对象是否包含 widthCredentials 属性,如果包含则支持 CORS。

1
var  xhrCors =  'withCredentials'  in  new  XMLHttpRequest();


在支持 CORS 的情况下,还需要服务端启用 CORS 支持。


假如我们想从 http://example.com 域中提交请求到 http://crossdomain.com 域,那么需要在 crossdomain.com 域中添加如下响应头:

1
Access-Control-Allow-Origion: http: //example.com


如果 crossdomain.com 要允许所有异域都可以 AJAX 请求该域资源,则添加如下响应头

1
Access-Control-Allow-Origion: *


服务端开启 CORS 支持后,在浏览器中我们就可以和提交普通的 AJAX 请求一样提交跨域请求了。

1
2
3
4
5
6
7
8
9
10
var  xhrCors =  'withCredentials'  in  new  XMLHttpRequest();
console.log(xhrCors);
 
var  xhr =  new  XMLHttpRequest();
xhr.open( 'GET' , 'http://www.crossdomain.com/hello.json' );
xhr.onload =  function (e){
     var  data = JSON.parse( this .response);
     //...
};
xhr.send();


7-2、XDomainRequest

如果想在 IE8、IE9中支持 CORS(IE10及以后版本支持 XHR2),我们可以使用 XDomainRequest(该属性目前已经废弃,不建议使用)。如果 vue-resource 不支持 XHR2,则会降级使用此种方式。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//实例化 XDomainRequest
var  xdr =  new  XDomainRequest();
xdr.open( 'get' , 'http://www.crossdomain.com/hello.json' );
xdr.onprogress =  function (){
     //进度回调
};
xdr.ontimeout =  function (){
     //超时回调
};
xdr.onerror =  function (){
     //出错回调
};
xdr.onload =  function (){
     //成功回调
     //success(xdr.responseText)
};
setTimeout( function (){
     //发送请求
     xdr.send();
},0)


注意:XDomain 只支持 GET 和 POST 两种请求,如果要在 vue-resource 中使用其他方法请求,需设置请求选项对象的 emulateHTTP 为true。在定时器中调用 xhr.send( )方法,是为了防止多个 XDomainRequest 请求同时发送时部分请求丢失。



8、Promise

vue-resource 调用 action 方法执行后都会返回一个 Promise 对象,该 Promise 对象提供了 then, catch, finally 等常用方法来注册回调函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
var  promise =  this .$http.post(
     'http://example.com/book/create' ,
     //请求体中要发送给服务端的数据
     {
         cat: '1' ,
         name: 'newbook'
     },
     {
         'headers' :{
             'Content-Type' : 'x-www-form-urlencoded'
         }
     }
);
promise.then(
         function (response){
             //成功回调
             console.log(response.data);
         },
         function (response){
             //失败回调
             console.log( 'something wrong' );
         }
);
promise. catch ( function (response){
     //失败回调
     console.log( 'something wrong' );
});
promise.finally( function (response){
     //执行完成或者失败回调后都会执行此逻辑
})


注意:所有回调函数的this 都指向组件实例



常见问题解析


1、如何发送 JSONP 请求

首先我们需要知道 JSONP 是利用 Javascript 可以跨域的特性从服务端请求数据的,也就是说,在跨域的情况下才有必要使用 JSONP来发送请求。vue-resource 提供了三种调用方式


1-1、全局方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Vue.http({
     url: 'http://example.com/books' ,
     //参数部分,将会拼接在 url 之后
     params:{
         cat: '1'
     },
     method: 'JSONP'
}).then( function (response){
     //response.data 为服务端返回的数据
     console.log(response.data);
}). catch ( function (response){
     //出错处理
     console.log(response)
})


1-2、实例底层方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
this .$http({
     url: 'http://example.com/books' ,
     //参数部分,将会拼接在 url 之后
     params:{
         cat: '1'
     },
     method: 'JSONP'
}).then( function (response){
     //response.data 为服务端返回的数据
     console.log(response.data);
}). catch ( function (response){
     //出错处理
     console.log(response)
})



1-3、实例便捷方法

1
2
3
4
5
6
7
8
9
10
11
12
13
this .$http.jsonp(
     'http://example.com/books' ,
     //参数部分,将会拼接在 url 之后
     {
         cat: '1'
     }
).then( function (response){
     //response.data 为服务端返回的数据
     console.log(response.data);
}). catch ( function (response){
     //出错处理
     console.log(response)
})


示例代码一:获取好搜的关键词(也就是常说的谷歌建议)


先打开 www.so.com 进入360 好搜的主页面,打开network查看页面请求,在搜索框中随便输入一个字母 v,获取请求发送的 url

wKiom1hEzjLwsXdsAACr0O4Tp3s238.pngwKioL1hEzj-yZQs4AADcr98BK0A882.png按照图中的步骤获取 url ,并截取 只包含回调函数 callback 和 关键字的字段

https://sug.so.360.cn/suggest?callback=suggest_so&word=v


在浏览器中打开这个链接,查看输入关键字 v,360搜索给出的搜索建议,可以看到所有的搜索建议关键词都存放在 s 这个数组中

wKiom1hEztGT3uFGAAA4LNMWb9s493.png我们现在想要实现的效果就是在我们的页面中,点击一个按钮就可以获取到上图中所有与 v 相关的关键词


代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<!DOCTYPE html>
< html >
< head  lang = "en" >
     < meta  charset = "UTF-8" >
     < meta  http-equiv = "X-UA-Compatible"  content = "IE=edge" >
     < meta  name = "viewport"  content = "width=device-width, initial-scale=1" >
     < link  href = "//cdn.bootcss.com/bootstrap/3.0.1/css/bootstrap.css"  rel = "stylesheet" >
     < title ></ title >
</ head >
< body >
< div  id = "app" >
     < input  class = "btn btn-primary"  type = "button"  value = "按钮"  @ click = "get" >
</ div >
 
< script  src = "//cdn.bootcss.com/vue/2.0.8/vue.js" ></ script >
< script  src = "//cdn.bootcss.com/vue-resource/0.7.2/vue-resource.js" ></ script >
< script >
     var vm = new Vue({
         el:'#app',
         methods:{
             get:function(){
                 this.$http.jsonp('https://sug.so.360.cn/suggest',{word:'v'})
                         .then(
                                 function(response){ //响应成功的回调函数
                                     alert(response.data.s); //关键词存放在data数据的s数组里面
                                 },
                                 function(response){ //响应失败的回调函数
                                     alert(response.status)
                                 }
                         )
             }
         }
     })
</ script >
</ body >
</ html >


点击按钮,发起 JSONP 请求,拿到了所有的关键词

wKioL1hE0L-AOKrmAACasO3Q0l0625.png

示例代码二:获取百度的关键词

同样的方法,打开 www.baidu.com ,打开控制台、进入 network,获取 url

wKioL1hE0uCzZzJ_AACrD53B7ng121.pngwKioL1hE0xHDVI0cAAHGXlFiBCY525.png

按照图中的步骤获取 url ,并截取 只包含回调函数 callback 和 关键字的字段。问题出现了,与360搜索不同的是,百度搜索的回调函数名称是 cb,不是callback

https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=v&cb=jQuery110208886270477889466_1480905136502


在浏览器中打开这个链接,查看输入关键字 v,百度搜索给出的搜索建议,可以看到所有的搜索建议关键词都存放在 s 这个数组中

wKiom1hE16WiLo7hAABWHQGATNU788.png


示例代码:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<!DOCTYPE html>
< html >
< head  lang = "en" >
     < meta  charset = "UTF-8" >
     < meta  http-equiv = "X-UA-Compatible"  content = "IE=edge" >
     < meta  name = "viewport"  content = "width=device-width, initial-scale=1" >
     < link  href = "//cdn.bootcss.com/bootstrap/3.0.1/css/bootstrap.css"  rel = "stylesheet" >
     < title ></ title >
</ head >
< body >
< div  id = "app" >
     < input  class = "btn btn-primary"  type = "button"  value = "按钮"  @ click = "get" >
</ div >
 
< script  src = "//cdn.bootcss.com/vue/2.0.8/vue.js" ></ script >
< script  src = "//cdn.bootcss.com/vue-resource/0.7.2/vue-resource.js" ></ script >
< script >
     var vm = new Vue({
         el:'#app',
         methods:{
             get:function(){
                 this.$http.jsonp('https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su',{wd:'v'})
                         .then(
                                 function(response){ //响应成功的回调函数
                                     alert(response.data.s); //关键词存放在data数据的s数组里面
                                 },
                                 function(response){ //响应失败的回调函数
                                     alert(response.status)
                                 }
                         )
             }
         }
     })
</ script >
</ body >
</ html >


同样的代码,但是运行之后并没有得到预期的结果,而是报错了:无法读取未定义的 sug 属性

wKioL1hE1IPCHYaaAADFnAyeQxM696.png


回忆下 4-2 options 参数列表中提到的 jsonp 默认值是 callback,再看看上面带下划线的文字,我们很快发现,百度中 回调函数的名称是cb,因此这里需要做一点小改动

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var  vm =  new  Vue({
     el: '#app' ,
     methods:{
         get: function (){
             this .$http.jsonp( 'https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su' ,{wd: 'v' },{jsonp: 'cb' })
                     .then(
                             function (response){  //响应成功的回调函数
                                 alert(response.data.s);  //关键词存放在data数据的s数组里面
                             },
                             function (response){  //响应失败的回调函数
                                 alert(response.status)
                             }
                     )
         }
     }
})


现在就都可以获取了

wKioL1hE1sfCnkjYAACfseuBw9U287.png

基于前面的两个例子,我们可以做一个稍微有点实用价值的demo,在页面中放一个搜索框,无论输入什么关键词,都能获取到百度的搜索建议


几个注意点:

(1)、input输入的内容不再是固定的字母 v,而是通过动态双向绑定到url中

(2)、当下拉列表的列表为0时,出现“暂无数据”提示

(3)、事件触发使用keyup(),按键松开时触发

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<!DOCTYPE html>
< html >
< head  lang = "en" >
     < meta  charset = "UTF-8" >
     < meta  http-equiv = "X-UA-Compatible"  content = "IE=edge" >
     < meta  name = "viewport"  content = "width=device-width, initial-scale=1" >
     < link  href = "//cdn.bootcss.com/bootstrap/3.0.1/css/bootstrap.css"  rel = "stylesheet" >
     < title ></ title >
</ head >
< body >
< div  id = "app" >
     < input  type = "text"  v-model = "word"  @ keyup = "get" >
     < ul >
         < li  v-for = "keyWord in keyWords" >`keyWord`</ li >
     </ ul >
     < p  v-show = "keyWords.length==0" >暂无数据……</ p >
</ div >
 
< script  src = "//cdn.bootcss.com/vue/2.0.8/vue.js" ></ script >
< script  src = "//cdn.bootcss.com/vue-resource/0.7.2/vue-resource.js" ></ script >
< script >
     var vm = new Vue({
         el:'#app',
         data:{
             keyWords:[],
             word:''
         },
         method:{
             get:function(){
                 this.$http.jsonp('https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?',{wd:this.word},{jsonp:'cb'})
                 .then(
                       function(response){
                           this.keyWords = response.data.s;
                       },
                       function(response){
                           alert(response.status)
                       }
                 )
             }
         }
     })
</ script >
</ body >
</ html >


初步的效果已经出来了

wKiom1hE3NvyeEG0AAA_a6E8kUk809.png

现在增加一个效果,当按下键盘下方向键时,对应的列表项会跟着变色


注意点:

(1)、Vue2.0中获取下标的方式是  (item, index) in items,没有$index

(2)、绑定多个class 的写法,可参照  http://dapengtalk.blog.51cto.com/11549574/1875451

(3)、当到了最后一个列表项时,就把 now设为-1,下次再按下方向键时,就切换到第一个列表项了

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<!DOCTYPE html>
< html >
< head  lang = "en" >
     < meta  charset = "UTF-8" >
     < meta  http-equiv = "X-UA-Compatible"  content = "IE=edge" >
     < meta  name = "viewport"  content = "width=device-width, initial-scale=1" >
     < link  href = "//cdn.bootcss.com/bootstrap/3.0.1/css/bootstrap.css"  rel = "stylesheet" >
     < title ></ title >
     < style >
         .gray{background:#ccc;}
     </ style >
</ head >
< body >
< div  id = "app" >
     < input  type = "text"  v-model = "word"  @ keyup = "get"  @ keydown.down = "changeColor" >
     < ul  class = "list-group" >
         < li  v-for = "(keyWord,index) in keyWords"  :class = "['list-group-item',{gray:index==now}]" >`keyWord`</ li >
     </ ul >
     < p  v-show = "keyWords.length==0" >暂无数据……</ p >
</ div >
 
< script  src = "//cdn.bootcss.com/vue/2.0.8/vue.js" ></ script >
< script  src = "//cdn.bootcss.com/vue-resource/0.7.2/vue-resource.js" ></ script >
< script >
     var vm = new Vue({
         el:'#app',
         data:{
             keyWords:[],
             word:'',
             now:-1,
         },
         methods:{
             get:function(){
                 this.$http.jsonp('https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?',{wd:this.word},{jsonp:'cb'})
                 .then(
                       function(response){
                           this.keyWords = response.data.s;
                       },
                       function(response){
                           alert(response.status)
                       }
                 )
             },
             changeColor:function(){
                 this.now++;
                 if(this.now == this.keyWords.length){ this.now = -1}
             }
         }
     })
</ script >
</ body >
</ html >


按下方向键,跟着变色

wKioL1hE5N-zuCpIAABKimI7z24483.png

现在想让按上方向键时,也出现变色的功能


注意点:

(1)、为了阻止index一直减,到了input时 index为-1,所以再往上翻也就是index为-2时,要把index切换到列表项的最后一个列表

(2)、为了阻止按键时,光标跑到了关键字的左边,所以要使用 .prevent 阻止冒泡

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<!DOCTYPE html>
< html >
< head  lang = "en" >
     < meta  charset = "UTF-8" >
     < meta  http-equiv = "X-UA-Compatible"  content = "IE=edge" >
     < meta  name = "viewport"  content = "width=device-width, initial-scale=1" >
     < link  href = "//cdn.bootcss.com/bootstrap/3.0.1/css/bootstrap.css"  rel = "stylesheet" >
     < title ></ title >
     < style >
         .gray{background:#ccc;}
     </ style >
</ head >
< body >
< div  id = "app" >
     < input  type = "text"  v-model = "word"  @ keyup = "get"  @ keydown.down = "changeColor"  @ keydown.up.prevent = "changeUpColor" >
     < ul  class = "list-group" >
         < li  v-for = "(keyWord,index) in keyWords"  :class = "['list-group-item',{gray:index==now}]" >`keyWord`</ li >
     </ ul >
     < p  v-show = "keyWords.length==0" >暂无数据……</ p >
</ div >
 
< script  src = "//cdn.bootcss.com/vue/2.0.8/vue.js" ></ script >
< script  src = "//cdn.bootcss.com/vue-resource/0.7.2/vue-resource.js" ></ script >
< script >
     var vm = new Vue({
         el:'#app',
         data:{
             keyWords:[],
             word:'',
             now:-1
         },
         methods:{
             get:function(){
                 this.$http.jsonp('https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?',{wd:this.word},{jsonp:'cb'})
                 .then(
                       function(response){
                           this.keyWords = response.data.s;
                       },
                       function(response){
                           alert(response.status)
                       }
                 )
             },
             changeColor:function(){
                 this.now++;
                 if(this.now == this.keyWords.length){ this.now = -1}
             },
             changeUpColor:function(){
                 this.now--;
                 if(this.now == -2){this.now = this.keyWords.length-1}
             }
         }
     })
</ script >
</ body >
</ html >


再加一个功能,随着选中不同的列表项,要跟着出现对应的搜索建议


注意点:

(1)、选中了哪个颜色的列表项,对应的内容就赋值给 word

(2)、在没有任何输入内容的情况下,按上下键时,要跳出循环,不应执行方法,否则会报错

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<!DOCTYPE html>
< html >
< head  lang = "en" >
     < meta  charset = "UTF-8" >
     < meta  http-equiv = "X-UA-Compatible"  content = "IE=edge" >
     < meta  name = "viewport"  content = "width=device-width, initial-scale=1" >
     < link  href = "//cdn.bootcss.com/bootstrap/3.0.1/css/bootstrap.css"  rel = "stylesheet" >
     < title ></ title >
     < style >
         .gray{background:#ccc;}
     </ style >
</ head >
< body >
< div  id = "app" >
     < input  type = "text"  v-model = "word"  @ keyup = "get"  @ keydown.down = "changeColor"  @ keydown.up.prevent = "changeUpColor" >
     < ul  class = "list-group" >
         < li  v-for = "(keyWord,index) in keyWords"  :class = "['list-group-item',{gray:index==now}]" >`keyWord`</ li >
     </ ul >
     < p  v-show = "keyWords.length==0" >暂无数据……</ p >
</ div >
 
< script  src = "//cdn.bootcss.com/vue/2.0.8/vue.js" ></ script >
< script  src = "//cdn.bootcss.com/vue-resource/0.7.2/vue-resource.js" ></ script >
< script >
     var vm = new Vue({
         el:'#app',
         data:{
             keyWords:[],
             word:'',
             now:-1
         },
         methods:{
             get:function(event){
                 if(event.keyCode==38 || event.keyCode==40){return};
                 this.$http.jsonp('https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?',{wd:this.word},{jsonp:'cb'})
                 .then(
                       function(response){
                           this.keyWords = response.data.s;
                       },
                       function(response){
                           alert(response.status)
                       }
                 )
             },
             changeColor:function(){
                 this.now++;
                 if(this.now == this.keyWords.length){ this.now = -1};
                 this.word = this.keyWords[this.now];
             },
             changeUpColor:function(){
                 this.now--;
                 if(this.now == -2){this.now = this.keyWords.length-1};
                 this.word = this.keyWords[this.now];
             }
         }
     })
</ script >
</ body >
</ html >

wKioL1hE7tawSFduAABEl5r4rU8313.png

最后再加一个功能,选中了哪个列表项,按回车即打开对应的百度搜索结果

注意:打开的页面url 如下图所示


wKioL1hE8Dmwy8OtAACBx_K69Mg849.png



最终代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
<!DOCTYPE html>
< html >
< head  lang = "en" >
     < meta  charset = "UTF-8" >
     < meta  http-equiv = "X-UA-Compatible"  content = "IE=edge" >
     < meta  name = "viewport"  content = "width=device-width, initial-scale=1" >
     < link  href = "//cdn.bootcss.com/bootstrap/3.0.1/css/bootstrap.css"  rel = "stylesheet" >
     < title ></ title >
     < style >
         .gray{background:#ccc;}
     </ style >
</ head >
< body >
< div  id = "app" >
     < input  type = "text"  v-model = "word"  @ keyup = "get"  @ keydown.down = "changeColor"  @ keydown.up.prevent = "changeUpColor" >
     < ul  class = "list-group" >
         < li  v-for = "(keyWord,index) in keyWords"  :class = "['list-group-item',{gray:index==now}]" >`keyWord`</ li >
     </ ul >
     < p  v-show = "keyWords.length==0" >暂无数据……</ p >
</ div >
 
< script  src = "//cdn.bootcss.com/vue/2.0.8/vue.js" ></ script >
< script  src = "//cdn.bootcss.com/vue-resource/0.7.2/vue-resource.js" ></ script >
< script >
     var vm = new Vue({
         el:'#app',
         data:{
             keyWords:[],
             word:'',
             now:-1
         },
         methods:{
             get:function(event){
                 if(event.keyCode==38 || event.keyCode==40){return};
                 if(event.keyCode==13){
                     window.open('https://www.baidu.com/s?wd='+this.word);
                     this.word='';
                 }
                 this.$http.jsonp('https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?',{wd:this.word},{jsonp:'cb'})
                 .then(
                       function(response){
                           this.keyWords = response.data.s;
                       },
                       function(response){
                           alert(response.status)
                       }
                 )
             },
             changeColor:function(){
                 this.now++;
                 if(this.now == this.keyWords.length){ this.now = -1};
                 this.word = this.keyWords[this.now];
             },
             changeUpColor:function(){
                 this.now--;
                 if(this.now == -2){this.now = this.keyWords.length-1};
                 this.word = this.keyWords[this.now];
             }
         }
     })
</ script >
</ body >
</ html >

wKiom1hE-0Ghk6kuAAhyBEKHS7E372.gif


2、如何修改发送给服务端的数据类型

在默认情况下,对于 PUT、POST、PATCH、DELETE等请求,请求头中的 Content-Type 为 application/json,即JSON 类型。有时候我们需要将数据提交为指定类型,如 application/x-www-form-urlencoded、mulitipart/form-data、text/plain等。下面以 POST 请求为例


2-1、全局 headers 配置

1
Vue.http.headers.post[ 'Content-Type' ]= 'application/x-www-form-urlencoded'


2-2、实例配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
this .$http.post(
     'http://example.com/books' ,
     //成功回调
     function (data,status,request){
         if (status == 200){
             console.dir(data);
         }
     },
     {
         //配置请求头
         headers:{
             'Content-Type' : 'multipart/form-data'
         }
     }
)


注意:实例配置的优先级高于全局配置,因此最终 Content-Type 为 multipart/form-data


3、$.http.post 方法变为 OPTIONS 方法

在跨域的情况下,对于非简单请求(PUT、DELETE、Content-Type 为 application/json),浏览器会在真实请求前,额外发起一次类型为 OPTIONS 的请求。只有服务器正确响应了 OPTIONS 请求后,浏览器才会发起真实请求。


因此,为了在跨域的情况下使用 POST 提交 Content-Type 为 application/json 的数据或 PUT、DELETE 等非简单请求,首先服务端需要开启 CORS 支持,同时需要设置如下响应头:

1
Access-Control-Allow-Methods: POST, GET, PUT, DELETE, OPTIONS



本文转自   frwupeng517   51CTO博客,原文链接:http://blog.51cto.com/dapengtalk/1878907
相关文章
|
3小时前
|
JSON JavaScript 前端开发
国际化:实现Vue应用的多语言支持
【4月更文挑战第23天】本文阐述了在Vue应用中实现多语言支持的重要性及步骤。使用vue-i18n插件,结合明确的语言需求和资源管理,实现文本翻译。配置路由和语言检测以支持用户切换,动态加载语言包以优化性能。同时考虑日期和货币格式化,确保全面的国际化体验。经过测试和持续维护,打造尊重文化多样性的全球化应用。
|
3小时前
|
缓存 监控 JavaScript
优化策略:提升Vue应用的性能和加载速度
【4月更文挑战第23天】本文探讨了优化Vue应用的策略,包括代码层面(精简代码、组件拆分、计算属性和侦听器)、路由懒加载、数据懒加载与防抖节流、图片和资源压缩及CDN、缓存机制的利用,以及使用Vue Devtools和性能分析工具进行监控与调试。通过这些方法,可以提升Vue应用的性能和加载速度,确保用户获得流畅体验。
|
3小时前
|
Web App开发 监控 JavaScript
【Node系列】创建第一个服务器应用
Node.js是一个基于Chrome V8引擎的JavaScript运行环境,可以用于构建高性能的网络应用程序。它采用事件驱动、非阻塞I/O模型,使得程序可以以高效地方式处理并发请求。
23 4
|
3小时前
|
弹性计算 负载均衡 容灾
应用阿里云弹性计算:打造高可用性云服务器ECS架构
阿里云弹性计算助力构建高可用云服务器ECS架构,通过实例分布、负载均衡、弹性IP、数据备份及多可用区部署,确保业务连续稳定。自动容错和迁移功能进一步增强容灾能力,提供全方位高可用保障。
19 0
|
3小时前
|
JavaScript
深入理解Vue生命周期钩子及其应用
深入理解Vue生命周期钩子及其应用
6 0
|
3小时前
|
JavaScript 前端开发
深入理解Vue生命周期钩子及其应用
深入理解Vue生命周期钩子及其应用
8 0
|
3小时前
|
开发框架 Java .NET
什么是JavaWeb(概念|应用|服务器)?
什么是JavaWeb(概念|应用|服务器)?
5 1
|
3小时前
|
弹性计算 运维 Java
Serverless 应用引擎产品使用之在Serverless 应用引擎中,将 Java 应用从 ECS 迁移到 SAE如何解决
阿里云Serverless 应用引擎(SAE)提供了完整的微服务应用生命周期管理能力,包括应用部署、服务治理、开发运维、资源管理等功能,并通过扩展功能支持多环境管理、API Gateway、事件驱动等高级应用场景,帮助企业快速构建、部署、运维和扩展微服务架构,实现Serverless化的应用部署与运维模式。以下是对SAE产品使用合集的概述,包括应用管理、服务治理、开发运维、资源管理等方面。
41 2
|
3小时前
|
弹性计算 运维 Serverless
Serverless 应用引擎产品使用之在阿里函数计算中,使用阿里云API或SDK从函数计算调用ECS实例的服务如何解决
阿里云Serverless 应用引擎(SAE)提供了完整的微服务应用生命周期管理能力,包括应用部署、服务治理、开发运维、资源管理等功能,并通过扩展功能支持多环境管理、API Gateway、事件驱动等高级应用场景,帮助企业快速构建、部署、运维和扩展微服务架构,实现Serverless化的应用部署与运维模式。以下是对SAE产品使用合集的概述,包括应用管理、服务治理、开发运维、资源管理等方面。
42 4
|
3小时前
|
运维 Serverless 文件存储
Serverless 应用引擎产品使用之阿里函数计算中stable. diffusion应用的服务器可以使用那种99元100G一年的道用型nas如何解决
阿里云Serverless 应用引擎(SAE)提供了完整的微服务应用生命周期管理能力,包括应用部署、服务治理、开发运维、资源管理等功能,并通过扩展功能支持多环境管理、API Gateway、事件驱动等高级应用场景,帮助企业快速构建、部署、运维和扩展微服务架构,实现Serverless化的应用部署与运维模式。以下是对SAE产品使用合集的概述,包括应用管理、服务治理、开发运维、资源管理等方面。
28 0