html异步读取json
在 HTML 页面中异步读取 JSON 数据,可以使用 JavaScript 中的 XMLHttpRequest(XHR)对象或 fetch API。
XMLHttpRequest 方法:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>异步读取 JSON</title>
</head>
<body>
<h1>异步读取 JSON</h1>
<script>
// 创建 XHR 对象
var xhr = new XMLHttpRequest();
// 设置请求方式和 URL
xhr.open('GET', 'data.json', true);
// 监听状态变化
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
// 将 JSON 字符串转换成 JavaScript 对象
var data = JSON.parse(xhr.responseText);
console.log(data);
}
};
// 发送请求
xhr.send();
</script>
</body>
</html>
fetch API 方法:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>异步读取 JSON</title>
</head>
<body>
<h1>异步读取 JSON</h1>
<script>
fetch('data.json')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
</script>
</body>
</html>
以上两种方法均可以实现异步读取 JSON 数据。使用 fetch API 可以更简洁地实现,并且支持 Promise,可更好地处理异步操作。
原文地址: https://www.cveoy.top/t/topic/ZpI 著作权归作者所有。请勿转载和采集!