教程 / 前端开发 / AJAX
XHR 响应:文本、XML和JSON的区别
完整解释responseText/responseXML及类型条件,安全读取XML节点并区分HTTP与解析失败。
本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。
学完这一章,你能够
- 按responseType使用合适的属性
- 处理null、空节点与非法数据
- 避免将响应字符串直接拼接成HTML
响应属性逐项比较
| 属性 | 得到什么 | 可用条件 | 异常/空值 |
|---|---|---|---|
| responseText | 字符串,可在下载过程中包含部分文本 | responseType为空串或text | 其它类型可能InvalidStateError;未完成不等于完整文本 |
| responseXML | 解析后的Document | document或默认类型且资源可按XML/HTML解析;浏览器主文档环境 | 未就绪/解析失败为null,类型不适用可能InvalidStateError |
| response | 由responseType决定的值 | 例如json、document、blob、arraybuffer、text | json解析失败可为null,须区别合法JSON null与失败上下文 |
XML也可以先作为文本读取,再由DOMParser解析。因此“非XML才用responseText”不是准确限制。Content-Type、responseType与实际字节都要一致;修改请求头不会把错误JSON自动变为XML。
文本、XML文档和JSON分支
在本地HTTP服务上实际发请求;完整页面、服务器和数据文件一并提供。下列代码与本节实例使用同一份JavaScript。
javascript · 阅读源码
"use strict";
const output=document.querySelector('#output');
const show=value=>{output.textContent=typeof value==='string'?value:JSON.stringify(value,null,2);};
const httpOK=xhr=>xhr.status>=200&&xhr.status<300;
let mbskyRun=0,mbskyActive=null;
document.querySelector('#run').onclick=()=>{const mbskyCurrent=++mbskyRun;mbskyActive?.abort();
const mode=document.querySelector('#mode').value;const xhr=new XMLHttpRequest();mbskyActive=xhr;
const url=mode==='text'?'/api/text':mode==='json'?'/data/courses.json':(mode==='xml'||mode==='raw-xml')?'/data/catalog.xml':'/data/invalid.xml';
xhr.open('GET',url,true);xhr.timeout=2000;xhr.responseType=mode==='xml'||mode==='invalid-xml'?'document':mode==='json'?'json':'text';
xhr.onload=()=>{if(mbskyCurrent!==mbskyRun)return;if(!httpOK(xhr)){show(`HTTP ${xhr.status}`);return;}
if(mode==='xml'||mode==='invalid-xml'){const doc=xhr.responseXML;if(!doc){show('XML无法解析:responseXML为null');return;}
show([...doc.getElementsByTagName('ARTIST')].map(node=>node.textContent));
}else if(mode==='json'){show(xhr.response===null?'响应不是有效JSON':xhr.response);}else show(xhr.responseText);
};
xhr.onerror=()=>{if(mbskyCurrent===mbskyRun)show('网络或CORS错误');};xhr.ontimeout=()=>{if(mbskyCurrent===mbskyRun)show('超时');};xhr.send();
};
window.addEventListener('pagehide',()=>{mbskyRun++;mbskyActive?.abort();});
分别处理文本、XML和JSON
所需环境:现代浏览器;本站Python标准库HTTP实验服务
当前源码 SHA256:36dd1c7905c650a8bebe924f1a6dfe849f9cbb293758c4f24944ace434d81505
预期结果 · 待实际运行核验
- text:完整文本字符串
- xml:艺术家列表保留空字符串,空元素不因childNodes[0]不存在而崩溃
- json:通过response读取JSON数组,不再访问不适用的responseText
- invalid-xml:显示解析失败,不将HTTP200等同XML有效
XML节点、空值和文本
javascript · 阅读源码
const doc = xhr.responseXML;
if (!doc) throw new Error("XML解析失败");
const artists = [...doc.getElementsByTagName("ARTIST")]
.map(element => element.textContent);
// 空元素合法,textContent为"";不要默认childNodes[0]一定存在。
getElementsByTagName按XML元素名匹配,大小写和命名空间需要按文档处理。childNodes包含文本、注释等节点,不保证第一个子节点就是完整业务文字;读取元素文本通常更适合textContent。列表显示采用新建li或文本节点,避免把数据中的尖括号当标记。
分层处理失败
- HTTP不是2xx:先按协议处理,不能继续解析为预期业务文档。
- HTTP成功但语法错误:XML为null或DOMParser生成parsererror;JSON可能抛异常或按responseType返回null。
- 语法合法但字段缺失:给出业务验证错误,不当作网络错误。
- 204和HEAD:没有响应体,不强行JSON.parse;status=0须考虑网络/CORS与当前环境。
Fetch读取XML的现代写法
javascript · 阅读源码
const response = await fetch("/data/catalog.xml");
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const xml = new DOMParser().parseFromString(await response.text(), "application/xml");
if (xml.querySelector("parsererror")) throw new Error("XML语法错误");
const titles = [...xml.getElementsByTagName("TITLE")].map(n => n.textContent);
这一段需要放在async函数或模块中。DOMParser返回独立文档,不等于内容已经安全插入页面;只有提取出的文本字段进入本站创建的节点。
常见错误与边界
- 访问json类型XHR的responseText。
- 直接访问responseXML.documentElement而不检查null。
- 把空ARTIST节点当采集丢失,或用innerHTML渲染不可信字段。
练习与解答
在catalog.xml增加一个空ARTIST元素,保证列表和表格仍保留该条记录。
展开参考解答
对元素使用textContent,元素缺失时用明确默认值;不能以childNodes[0].nodeValue无条件读取。