本文主要介绍的是在 vue2.0Jsonp 的使用方法, 通过 github 引入 jsonp 和 promise 封装, 实现跨域获取数据.
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 指令, 并重新运行项目
- npm install
- npm run dev
2.2 封装 jsonp.js
- 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 两个文件.
- 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
- <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 请求成功结果
以上为 vue2.0 jsonp 简单使用方式, 实例下载链接
总结
以上所述是小编给大家介绍的 VUE2.0 中 Jsonp 的使用方法, 希望对大家有所帮助, 如果大家有任何疑问请给我留言, 小编会及时回复大家的. 在此也非常感谢大家对脚本之家网站的支持!
来源: http://www.jb51.net/article/140607.htm