AJAX (Asynchronous JavaScript and XML) 是一种在不重新加载整个页面的情况下与服务器交换数据并更新部分网页的技术。虽然名称中包含XML,但现在更常用JSON格式进行数据交换。
最可靠的方法是检查HTTP响应头中的Content-Type
字段。合法的JSON响应应该包含application/json
内容类型。
fetch('https://api.example.com/data')
.then(response => {
const contentType = response.headers.get('content-type');
if (contentType && contentType.includes('application/json')) {
return response.json();
}
throw new TypeError("Oops, we haven't got JSON!");
})
.then(data => {
// 处理JSON数据
console.log(data);
})
.catch(error => {
console.error('Error:', error);
});
如果响应头不可靠或缺失,可以尝试解析响应文本:
function isJSON(str) {
try {
JSON.parse(str);
return true;
} catch (e) {
return false;
}
}
fetch('https://api.example.com/data')
.then(response => response.text())
.then(text => {
if (isJSON(text)) {
const data = JSON.parse(text);
// 处理JSON数据
} else {
// 处理非JSON响应
}
});
如果使用jQuery,可以利用其内置的JSON检测:
$.ajax({
url: 'https://api.example.com/data',
dataType: 'json', // 期望JSON响应
success: function(data) {
// 成功获取JSON数据
},
error: function(xhr, status, error) {
// 处理错误,包括非JSON响应
if (xhr.responseText) {
try {
JSON.parse(xhr.responseText);
// 实际上是JSON,可能是其他错误
} catch (e) {
// 确实不是JSON
}
}
}
});
Content-Type
头,客户端可能无法识别。Content-Type
响应头