蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

XHR读取对象并检查readyState

JAVASCRIPT本地HTTP服务;完整对象数据site.json存在index.html
index.html27 行
"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.onreadystatechange = function () {
  if (xhr.readyState !== 4) return;
  if (xhr.status < 200 || xhr.status >= 300) {
    show("HTTP错误", xhr.status);
    return;
  }
  try {
    const data = JSON.parse(xhr.responseText);
    if (!data || typeof data.name !== "string" || !Array.isArray(data.sites)) throw new TypeError("期待含字符串name与sites数组的对象");
    show("服务端名称", data.name);
    show("站点数", data.sites.length);
  } catch (error) { show("数据错误", error.message); }
};
xhr.onerror = () => show("网络错误", "请求未完成");
xhr.open("GET", "./site.json", true);
xhr.send();
本例需在 本地HTTP服务;完整对象数据site.json存在 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:本地HTTP服务;完整对象数据site.json存在

入口文件:examples/0dc1a1afb33b6a14bd742052/xhr-object/index.html

本例采用完整 HTML 文档,样式和脚本在 HTML 源码中维护。

预期结果与验证条件观察提示
  • 正常HTTP完成时输出服务端名称: 蓝色天空网
  • 站点数: 3
  • readyState未到4不读取;HTTP、解析和网络失败有分支

请结合实际环境逐项观察。

附件与关联工程包下载

下载课程关联工程包:JSON

课程关联工程包(登记关联11章) · 含当前章节或实例 · mbskycom202611a250.zip

下载课程关联工程包:JSON

课程关联工程包(登记关联11章) · 含当前章节或实例 · mbskycom202611a438.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习