
本文详解 XMLHttpRequest 发送 GET 请求时无法获取响应的根本原因——未监听 load 事件导致同步读取未就绪的响应体,并提供完整可运行的修复方案与最佳实践。
本文详解 xmlhttprequest 发送 get 请求时无法获取响应的根本原因——未监听 `load` 事件导致同步读取未就绪的响应体,并提供完整可运行的修复方案与最佳实践。
在使用 XMLHttpRequest 发起网络请求时,一个常见却极易被忽视的错误是:在请求尚未完成时就尝试访问 xhr.responseText。你的代码正是如此——xhr.send() 是异步操作,而后续的 const response = xhr.responseText; 等语句紧随其后立即执行,此时服务器响应还未返回,responseText 为空字符串,进而导致 indexOf("Census Tracts") 返回 -1,substr(-1, 11) 抛出异常或返回意外结果,且 onerror 不会触发(因为请求已发出,只是无有效响应)。
✅ 正确做法是:将响应处理逻辑放在 xhr.onload 事件处理器中。该事件仅在请求成功完成(HTTP 状态码 200–299)且响应体完全接收后触发。
以下是修复后的完整代码(含健壮性增强):
<html>
<body>
<label for="streetInput">Street:</label>
<input type="text" id="streetInput"><br><br>
<label for="cityInput">City:</label>
<input type="text" id="cityInput"><br><br>
<label for="stateInput">State:</label>
<input type="text" id="stateInput"><br><br>
<label for="zipInput">Zip:</label>
<input type="text" id="zipInput"><br><br>
<button onclick="searchCensusData()">Search Census Data</button>
<p id="result"></p>
<script>
function searchCensusData() {
const street = encodeURIComponent(document.getElementById('streetInput').value).replace(/%20/g, '+');
const city = encodeURIComponent(document.getElementById('cityInput').value);
const state = encodeURIComponent(document.getElementById('stateInput').value);
const zip = encodeURIComponent(document.getElementById('zipInput').value);
const benchmark = "Public_AR_Current";
const vintage = "Current_Current";
const format = "json";
// 构建标准 URL(注意:+ 替换空格仅适用于 street 参数;其他参数保持标准编码)
const apiUrl = `https://geocoding.geo.census.gov/geocoder/geographies/address?` +
`street=${street}&city=${city}&state=${state}&zip=${zip}` +
`&benchmark=${benchmark}&vintage=${vintage}&format=${format}`;
document.getElementById('result').innerText = `Requesting: ${apiUrl}`;
const xhr = new XMLHttpRequest();
xhr.open("GET", apiUrl);
// ✅ 成功响应处理:必须在 onload 中读取 responseText
xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 300) {
try {
const data = JSON.parse(xhr.responseText);
// 示例:提取 Census Tract(实际结构请参考 Census API 文档)
const tract = data.result?.addressMatches?.[0]?.geographies?.["Census Tracts"]?.[0]?.TRACT;
document.getElementById('result').innerText =
tract ? `Census Tract: ${tract}` : "No census tract found.";
} catch (e) {
document.getElementById('result').innerText =
`Invalid JSON response: ${e.message}`;
}
} else {
document.getElementById('result').innerText =
`HTTP Error: ${xhr.status} ${xhr.statusText}`;
}
};
// ✅ 网络层错误(如 DNS 失败、连接中断)
xhr.onerror = function() {
document.getElementById('result').innerText = "Network Error: Request failed.";
};
// ✅ 超时处理(可选但推荐)
xhr.timeout = 10000;
xhr.ontimeout = function() {
document.getElementById('result').innerText = "Request timed out.";
};
xhr.send(); // 发起请求
}
</script>
</body>
</html>⚠️ 关键注意事项:
-
不要在
send()后直接读取responseText—— 它只在load或readystatechange(当readyState === 4)之后才可用; -
优先使用
fetch()替代XMLHttpRequest:现代项目推荐使用fetch()+async/await,语法更简洁、Promise 原生支持更易错误处理; -
Census API 对跨域(CORS)有限制:浏览器直连可能因 CORS 被拒(返回
Failed to fetch),生产环境建议通过后端代理转发请求; -
URL 编码规范:
+在 URL 中等价于空格,但仅适用于application/x-www-form-urlencoded场景;REST API 推荐统一使用%20,此处为兼容 Census 接口要求保留+,但需确保仅用于street参数(其他参数仍用标准encodeURIComponent); -
始终校验
xhr.status和 JSON 解析结果,避免因服务端返回非 2xx 状态码或格式异常导致脚本崩溃。
掌握事件驱动的异步处理逻辑,是前端网络编程的基石。从 onload 入手,你就能稳定、可靠地与任何 RESTful API 交互。

















