Promise版 jsonp
参数
参数名 | 参数类型 | 参数说明 |
---|---|---|
url | string | url 地址 |
callbackKey | string -默认值callback | url 回调函数的key |
callbackName | string | 回调函数名 |
params | any | url 参数 |
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];
};
});
}