js如何获取网页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格式并输出到控制台
原文地址: https://www.cveoy.top/t/topic/g1Ld 著作权归作者所有。请勿转载和采集!