jQuery 的 getJSON()
方法是 $.ajax()
的一个简写形式,专门用于获取 JSON 数据。它默认使用 GET 请求方式,并自动将响应解析为 JavaScript 对象。
基本语法:
$.getJSON(url, [data], [successCallback]);
jQuery 的 getJSON()
方法本身不支持直接设置超时参数,但可以通过以下方式实现:
$.ajax({
url: 'your-api-endpoint',
dataType: 'json',
type: 'GET',
timeout: 5000, // 设置超时时间为5秒
success: function(data) {
console.log('成功获取数据:', data);
},
error: function(jqXHR, textStatus, errorThrown) {
if (textStatus === 'timeout') {
console.error('请求超时');
} else {
console.error('请求失败:', textStatus, errorThrown);
}
}
});
function getJSONWithTimeout(url, timeout) {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
reject(new Error('请求超时'));
}, timeout);
$.getJSON(url)
.done(data => {
clearTimeout(timer);
resolve(data);
})
.fail((jqXHR, textStatus, error) => {
clearTimeout(timer);
reject(error);
});
});
}
// 使用示例
getJSONWithTimeout('your-api-endpoint', 5000)
.then(data => console.log(data))
.catch(error => console.error(error));
问题1:超时后请求仍在后台继续
var xhr = $.ajax({ /* 参数 */ });
setTimeout(function() {
xhr.abort(); // 手动中止请求
}, 5000);
问题2:跨域请求超时无效
问题3:超时时间设置不合理
通过以上方法,您可以有效地在 jQuery 中实现带超时功能的 JSON 数据获取,提升应用的健壮性和用户体验。