1.先cnpm install jsonp --save
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) } }) }) } export 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) : '' }
3.在组件中使用jsonp获取数据
<template> <div id="app"> hello </div> </template> <script> import jsonp from './assets/base/js/jsonp' export default { name: 'App', created:function () { getRecommend(); } } function getRecommend(){ const url = 'https://c.y.qq.com/musichall/fcgi-bin/fcg_yqqhomepagerecommend.fcg' const data = {} const options = { param: 'jsonpCallback' } console.log(jsonp(url, data, options)) } </script> <style> </style>
4.jsonp.js是用别人写好的代码,当然第三部分可以拆分,将getRecommend函数单独放到外面,和其它函数一块,引入时如下
import {getRecommend, getDiscList} from 'api/recommend'
5.发现一个问题,
?、
数据格式这样,怎么获取呢?
<template> <div id="app"> hello </div> </template> <script> import jsonp from './assets/base/js/jsonp' export default { name: 'App', created:function () { getRecommend().then((res) => { console.log(res); }) } } function getRecommend(){ const url = 'https://c.y.qq.com/musichall/fcgi-bin/fcg_yqqhomepagerecommend.fcg' const data = {} const options = { param: 'jsonpCallback' } return jsonp(url, data, options) } </script> <style> </style>
.then是jsonp函数返回的对象自带的
好了,简单的跨域获取数据就这样了,具体我也不清楚,哈哈,继续学习。