"use strict";
const output = document.querySelector("#output");
function show(label, value) {
let text;
if (typeof value === "undefined") text = "undefined";
else if (typeof value === "number" && !Number.isFinite(value)) text = String(value);
else if (typeof value === "string") text = value;
else text = JSON.stringify(value);
output.textContent += label + ": " + text + "\n";
}
const xhr = new XMLHttpRequest();
xhr.open("GET", "./sites.json");
xhr.responseType = "text";
xhr.onload = () => {
try {
if (xhr.status < 200 || xhr.status >= 300) throw new Error("HTTP " + xhr.status);
const values = JSON.parse(xhr.responseText);
if (!Array.isArray(values) || typeof values[1] !== "string") throw new TypeError("期待至少两项字符串数组");
show("第二项", values[1]);
} catch (error) { show("数据错误", error.message); }
};
xhr.onerror = () => show("网络错误", "请求未完成");
xhr.send();
本例需在 本地HTTP服务;sites.json存在 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:本地HTTP服务;sites.json存在
入口文件:examples/0dc1a1afb33b6a14bd742052/xhr-array/index.html
本例采用完整 HTML 文档,样式和脚本在 HTML 源码中维护。
预期结果与验证条件观察提示
- HTTP成功时输出第二项: 学习
- 网络错误、HTTP失败、JSON解析失败和业务形状错误有分支
请结合实际环境逐项观察。
附件与关联工程包下载
课程关联工程包(登记关联11章) · 含当前章节或实例 · mbskycom202611a250.zip
课程关联工程包(登记关联11章) · 含当前章节或实例 · mbskycom202611a438.zip