Skip to content

Promise版 jsonp

参数

参数名参数类型参数说明
urlstringurl地址
callbackKeystring-默认值callbackurl回调函数的key
callbackNamestring回调函数名
paramsanyurl参数
paramsSerializer(params: any) => string自定义参数序列化

源代码&使用

ts
import { jsonp } from "@manzhixing/utilsxy"

// 调用 百度搜索🔍API
jsonp({
    url: 'https://suggestion.baidu.com/su',
    callbackKey: 'cb',
    callbackName: 'callback',
    params: {
        wd: "chengbotao"
    }
}).then(data => {
    console.log(data);
})
ts
/*
 * @Author: Chengbotao
 * @Contact: https://github.com/chengbotao
 */
import { buildURL } from '../buildURL';

interface JsonpOpts {
  url: string;
  callbackName: string;
  callbackKey?: string;
  params?: any;
  paramsSerializer?: (params: any) => string;
}

declare global {
  interface Window {
    [key: string]: unknown;
  }
}

export function jsonp(options: JsonpOpts) {
  const { url, callbackKey = 'callback', callbackName, params, paramsSerializer } = options;
  return new Promise((resolve, reject) => {
    const scriptEl = document.createElement('script');
    scriptEl.src = `${buildURL(url, params, paramsSerializer)}&${callbackKey}=${callbackName}`;
    document.body.appendChild(scriptEl);
    window[callbackName] = (data: any) => {
      resolve(data);
      document.removeChild(scriptEl);
      delete window[callbackName];
    };
  });
}