function jsonp(url, options = {}) {
return new Promise((resolve, reject) => {
// 生成唯一回调函数名
const callbackName = `jsonp_callback_${Date.now()}_${Math.random().toString().replace('.', '')}`;
// 处理URL参数
const params = new URLSearchParams(options.params || {});
params.append(options.callbackParam || 'callback', callbackName);
// 创建script标签
const script = document.createElement('script');
script.src = `${url}?${params}`;
// 挂载回调函数到window
window[callbackName] = (data) => {
try {
resolve(data);
} finally {
// 清理
cleanup();
}
};
// 错误处理
script.onerror = (error) => {
reject(new Error(`JSONP请求失败: ${error.message}`));
cleanup();
};
// 超时处理
if (options.timeout) {
const timeoutId = setTimeout(() => {
reject(new Error('JSONP请求超时'));
cleanup();
}, options.timeout);
script.onload = () => clearTimeout(timeoutId);
}
// 清理函数
function cleanup() {
// 移除script标签
script.remove();
// 删除全局回调函数
delete window[callbackName];
}
// 添加到文档中触发请求
document.head.appendChild(script);
});
}
// 使用示例
jsonp('https://api.example.com/data', {
params: {
key: 'value',
format: 'json'
},
callbackParam: 'jsonpCallback',
timeout: 5000
})
.then(data => console.log('JSONP响应:', data))
.catch(error => console.error('JSONP错误:', error));
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。