JavaScript 获取网页 JSON 数据教程
可以使用 JavaScript 中的 XMLHttpRequest 对象或 fetch API 来获取网页 JSON 数据。
使用 XMLHttpRequest 对象:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://example.com/data.json', true);
xhr.onload = function() {
if (xhr.status === 200) {
var data = JSON.parse(xhr.responseText);
console.log(data);
}
};
xhr.send();
使用 fetch API:
fetch('http://example.com/data.json')
.then(function(response) {
return response.json();
})
.then(function(data) {
console.log(data);
});
其中,第一行使用 fetch 函数来获取数据,返回一个 Promise 对象。然后使用 then 方法来处理返回的数据,将其解析为 JSON 格式并输出到控制台。
原文地址: http://www.cveoy.top/t/topic/fYf4 著作权归作者所有。请勿转载和采集!