JavaScript 读取远程 JSON 数据通常是通过发起 HTTP 请求来实现的。最常用的方法是使用 XMLHttpRequest
对象或现代的 fetch
API。
fetch
APIfetch('https://api.example.com/data.json')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('There has been a problem with your fetch operation:', error));
XMLHttpRequest
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data.json', true);
xhr.onload = function () {
if (this.status == 200) {
var data = JSON.parse(this.responseText);
console.log(data);
} else {
console.error('Error:', this.statusText);
}
};
xhr.onerror = function () {
console.error('Request failed');
};
xhr.send();
原因:浏览器的安全策略阻止了从一个源加载的脚本去访问另一个源的资源。
解决方法:
原因:可能是网络问题,或者服务器没有响应。
解决方法:
原因:服务器返回的数据可能不是有效的 JSON 格式。
解决方法:
try...catch
语句捕获解析错误。fetch('https://api.example.com/data.json')
.then(response => response.text())
.then(text => {
try {
var data = JSON.parse(text);
console.log(data);
} catch (e) {
console.error('Invalid JSON:', e);
}
})
.catch(error => console.error('Fetch error:', error));
通过以上方法,可以有效地处理 JavaScript 读取远程 JSON 数据时可能遇到的各种问题。
领取专属 10元无门槛券
手把手带您无忧上云