1.JSONP的用途和原理
使用JSONP主要是目的通過動態創建Script,動態拼接url,進而抓取數據,實現跨域。確切地說,AJAX請求由於同源影響,是不允許進行跨域請求的,而Script標籤src屬性中的鏈接卻可以訪問跨域的js腳本,利用這一特性,服務端不再返回JSON格式的數據,而是返回一段調用某個函數的JS代碼,在src屬性中進行調用,實現跨域。
2.JSONP的使用方法
2.1 引入github的jsonp
打開項目>package.json>在”dependencies”下添加代碼
"jsonp": "^0.2.1"
如圖所示,然後執行安裝cmd指令,並重新運行項目
?
1
2
|
npm install
npm run dev
|
2.2 封裝jsonp.js
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
import originJSONP from 'jsonp'
export default function jsonp(url, data, option) {
url += (url.indexOf( '?' ) < 0 ? '?' : '&' ) + param(data)
return new Promise((resolve, reject) => {
originJSONP(url, option, (err, data) => {
if (!err) {
resolve(data)
} else {
reject(err)
}
})
})
}
function param(data) {
let url = ''
for ( var k in data) {
let value = data[k] !== undefined ? data[k] : ''
url += `&${k}=${encodeURIComponent(value)}`
}
// 刪除第一個&
return url ? url.substring(1) : ''
}
|
目錄結構如下:
2.3 jsonp.js的API調用
在src的文件夾下創建api文件夾,用於儲存api調用的js,新建config.js和recommend.js兩個文件。
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
config.js
export const commonParams = {
g_tK: 5381,
inCharset: 'utf-8' ,
outCharset: 'utf-8' ,
notice: 0,
format: 'jsonp'
}
export const options = {
param: 'jsonpCallback'
}
export const ERR_OK = 0
recommend.js
import jsonp from 'common/js/jsonp'
import {commonParams, options} from './config'
export function getRecommend() {
const url = 'https://c.y.qq.com/musichall/fcgi-bin/fcg_yqqhomepagerecommend.fcg' //此處的url可以自行修改,本文是qq音樂鏈接
const data = Object.assign({}, commonParams, {
platform: 'h5' ,
uin: 0,
needNewCode: 1
})
return jsonp(url, data, options)
}
|
目錄結構如下:
2.4 recommend.vue文件調用
在項目目錄下的src>components>recommend>
對應的文件.vue
recommend.vue
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
<template>
<div class= "recommend" >
recommend
</div>
</template>
<script type= "text/ecmascript-6" >
import {getRecommend} from 'api/recommend'
import {ERR_OK} from 'api/config'
export default {
name: 'recommend' ,
created() {
this ._getRecommend()
},
methods: {
_getRecommend() {
getRecommend().then((res) => {
if (res.code === ERR_OK) {
console.log(res.data.slider)
}
})
}
}
}
</script>
|
2.5 頁面jsonp請求成功結果