VUE JSONP知识点详解

JSONP

jsop介绍

jsonp原理

jsonp发送到并不是一个ajax请求,它其实是创建一个动态script标签(script标签没有同源策略限制),script指向真实服务端地址,和普通的ajax地址的区别在于:在地址后面有一个参数(如:callback=a),会在返回的数据里面调用a去包裹一个方法,包裹一段数据,相当于在前端执行a这个方法,但是前端是没有a这个方法的,所以在发送请求之前,在windows上去注册一个a方法,那么就可以在服务端返回方法a之前就可以在windwos上定义的a方法中获取数据了。

jsonp实现库API
jsonp(url,opts,fn)
  • url (String) url to fetch
  • opts (Object), optional
    。param (String) name of the query string parameter to specify the callback (defaults to callback)
    。timeout (Number) how long after a timeout error is emitted. 0 to disable (defaults to 60000)
    。prefix (String) prefix for the global callback functions that handle jsonp responses (defaults to __jp)
    。name (String) name of the global callback functions that handle jsonp responses (defaults to prefix + incremented counter)
  • fn callback
    The callback is called with err, data parameters.
    If it times out, the err will be an Error object whose message is Timeout.
    Returns a function that, when called, will cancel the in-progress jsonp request (fn won't be called).
vue实现
packge.json配置
dependencies": {
    "jsonp": "0.2.1"
  }
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) : ''
}
jsonp调用
  • 公共参数配置
export const commonParams = {
  g_tk: 1928093487,
  inCharset: 'utf-8',
  outCharset: 'utf-8',
  notice: 0,
  format: 'jsonp'
}

export const options = {
  param: 'jsonpCallback'
}

export const ERR_OK = 0

你可能感兴趣的:(VUE JSONP知识点详解)