目录
基本概念
这里关于jsonp请看这篇博文:https://blog.csdn.net/qq78442761/article/details/102067313
代码与实例
这里把数据打印到控制台:
程序结构如下:
源码如下:
config.js
- export const commonParams = {
-
- pre: 1,
- p: 3,
- ie: 'utf-8',
- json: 1,
- prod: 'pc',
- from: 'pc_web'
- }
-
- export const options = {
-
- // cb: 'jQuery110206443125406022925_1570194853214',
- // wd: '12'
- }
json.js
- import originJsonp from 'jsonp'
-
- export default function jsonp(url, data) {
-
- url += (url.indexOf('?') < 0 ? '?' : '&') + param(data);
-
- return new Promise((resolve, reject) =>{
-
- originJsonp(url, (err, data) => {
-
- if(!err){
-
- resolve(data);
- }
- else{
-
- reject(err);
- }
- })
- })
- }
-
- export function param(data) {
-
- let url = '';
- for(let k in data){
-
- let value = data[k] !== undefined ? data[k] : '';
- url += '&' + k + '=' + encodeURIComponent(value);
- }
-
- return url ? url.substring(1) : '';
- }
test.js
- import jsonp from '../common/jsonp'
- import {commonParams} from "./config"
-
- export function testRe() {
-
- const url = "https://www.baidu.com/sugrec";
- const data = Object.assign({}, commonParams, {
-
- //可以添加变动的get数据
- wd: '123'
- })
-
-
- return jsonp(url, data)
- }
Test.vue
- <template>
- <div>
- <h1>Hello world</h1>
- </div>
- </template>
-
- <script>
-
- import {testRe} from '../common/test'
-
- export default {
-
- created() {
-
- this._getRecommend();
- },
- methods: {
-
- _getRecommend(){
-
- testRe().then((res) => {
-
- console.log(res);
- })
- }
- }
- }
- </script>
index.js
- import Vue from 'vue'
- import Router from 'vue-router'
- import HelloWorld from '@/components/HelloWorld'
- import Test from '@/components/Test'
-
- Vue.use(Router)
-
- export default new Router({
- routes: [
- {
- path: '/',
- name: 'Test',
- component: Test
- // name: 'HelloWorld',
- // component: HelloWorld
- }
- ]
- })