[Vue项目][Jayee-Music]jsonp的引入、封装

本文介绍了在Vue项目中如何引入和封装jsonp。首先,在`package.json`的`dependencies`中添加jsonp库,然后在`src/common/js`目录下创建`jsonp.js`文件进行封装。封装的jsonp API包括url、opts和fn参数,其中opts提供了超时时间、回调函数名等配置。同时,文章还展示了使用Promise封装的jsonp源码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、在package.json的"dependencies"中添加jsonp

在这里插入图片描述

在Terminal中运行

npm install
二、jsonp的封装
1.在src/common/js目录下新建一个js文件,命名为jsonp.js

在这里插入图片描述

2.jsonp的API:

jsonp(url, opts, fn)

  • url (String) url to fetch(用于获取的url
  • opts (Object), optional (选项,有下面四个
  1. param (String) name of the query string parameter to specify the
    callback (defaults to callback)(用于指定回调的查询字符串参数的名称

  2. timeout (Number) how long after a timeout error is emitted. 0 to disable (defaults to 60000) (超时时间,默认一分钟

  3. prefix (String) prefix for the global callback functions that handle jsonp responses (defaults to __jp) (处理jsonp响应的全局回调函数的前缀,默认__jp
    name (String) name of the global callback functions that handle jsonp responses (defaults to prefix + incremented counter) (处理jsonp响应的全局回调函数的名称,默认prefix + incremented counter

  4. fn callback
    The callback is called with err, data parameters.(回调函数,有errdata两个参数

If it times out, the err will be an Error object whose message is Timeout.
如果超时, err 将是一个Error 对象,其messageTimeout。**)
Returns a function that, when called, will cancel the in-progress jsonp request (fn won’t be called).
返回一个函数,该函数在调用时将取消正在进行的jsonp请求(’ fn '不会被调用)
参考:https://github.com/webmodules/jsonp

3.用Promise封装jsonp以及url拼接方法的源码:
import originJSONP from 'jsonp' // 从我们npm安装的jsonp中引入originJSONP(原始jsonp)

export default function jsonp(url, data, option) {
  /*
 * url为基础地址
 * 所有的query放到data中,再和url通过自定义的函数param()拼接在一起
 * option对应的是jsonp的参数option
 */

  url += (url.indexOf('?') < 0 ? '?' : '&') + param(data)
  // 如果没有'?'则加一个'?',如果有则拼一个'&'(因为param()方法中去掉了第一个&)

  return new Promise((resolve, reject) => {
    // 成功时调用resolve,失败调用reject
    // eslint-disable-next-line handle-callback-err
    originJSONP(url, option, (err, data) => {
      // 请求成功时err为null
      if (!err) { // 请求成功时
        resolve(data)
      } else {
        reject(err)
      }
    })
  })
}

/*
* function param ()
* 用于拼接query到url中
*/
function param (data) {
  let url = ''
  for (var k in data) {
    let value = data[k] !== undefined ? data[k] : ''
    // 如果不为undefined则赋值给value,如果为undefined则value赋值为空
    url += `&${k}=${encodeURIComponent(value)}`
    // es6语法,将value拼接到url上,每个value前加上&
  }
  return url ? url.substring(1) : ''
  // 返回url,url不为空则返回url并且去掉第一个&,url为空则返回空字符串
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值