生成随机回调函数名,避免回调函数名相同造成获取返回数据混乱
const makeCallbackName = () => {
const timestamp = Date.now();
const randomNum = Math.round(Math.random() * 1000);
return `callback_${timestamp}_${randomNum}`;
}
jsonp解决跨域
export const jsonpReq = () => {
// 接口请求地址
const reqInterface = 'xxxxx'
const callbackName = makeCallbackName();
try {
return new Promise((resolve, reject) => {
// 后端调用callback返回数据
window[callbackName] = (result: any) => {
resolve(result);
}
const JSONP = document.createElement('script');
JSONP.type = 'text/javascript';
JSONP.src = `${reqInterface}?callback=${callbackName}`;
document.body.appendChild(JSONP);
setTimeout(() => {
document.body.removeChild(JSONP)
}, 100)
})
} catch (error) {
console.log('JSONP error-----', error);
}
};
使用
const getJsonpData = async () => {
const res = await jsonpReq();
console.log('res----', res)
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。