function JSONP({url, params, callbackKey, callback}) {
params = params || {}
params[callbackKey] = "jsonpCallback"
window.jsonpCallback = callback
const paramKeys = Object.keys(params)
const paramString = paramKeys.map(key => `${key}=${params[key]}`).join('&')
script.setAttribute('src', `${url}?${paramString}`)
document.body.appendChild(script)
script.onerror = () => {
window.jsonpCallback({ code: 500, msg: '请求失败' })
document.body.removeChild(script)
}
}
JSONP ({
url : 'http://'
params: {}
callbackKey: 'cb'
callback(result) {
Vue.prototype.$result = result
}
})
判断JSONP响应成功与响应失败的方法
<!DOCTYPE html>
<html>
<head>
<title>JSONP 跨域请求示例</title>
</head>
<body>
<script>
// 定义全局变量控制请求状态
let jsonpSuccess = false;
let jsonpTimeout = false;
let jsonpTimer;
// 定义 JSONP 回调函数(全局作用域)
window.jsonpCallback = (data) => {
// 清除超时计时器
clearTimeout(jsonpTimer);
// 标记成功
jsonpSuccess = true;
// 执行后续代码
executeAfterResponse;
};
// 发送跨域请求(JSONP)
function sendJsonpRequest(url) {
// 创建 script 标签
const script = document.createElement('script');
script.src = ` $ {url}?callback=jsonpCallback`;
// 将 script 标签插入文档
document.head.appendChild(script);
// 设置超时处理(假设 5 秒超时)
jsonpTimer = setTimeout( => {
// 请求超时
jsonpTimeout = true;
handleFailure('处理请求超时');
// 清除 script标签
document.head.removeChild(script);
}, 5000);
};
// 处理请求超时或失败逻辑
function handleFailure(error) {
console.error('请求失败:', error);
};
// 响应完成后的代码
function executeAfterResponse {
if (jsonpSuccess) {
console.log('继续执行后续代码');
} else if (jsonpTimeout) {
handleFailure('请求超时');
}
};
// 触发请求
sendJsonpRequest('https://api.example.com/data');
</script>
</body>
</html>