您好!欢迎访问家园网-www.jy.wang!

家园网

XMLHttpRequest.responseText 属性扩展示例

网络 作者:本站 点击:

XMLHttpRequest.responseText 属性扩展示例

基础文本响应示例

const xhr1 = new XMLHttpRequest();
xhr1.open('GET', '/api/notice', true);
xhr1.onload = function() {
  console.log('示例1 - 公告文本:');
  console.log(xhr1.responseText); 
};
xhr1.send();
// 输出可能:
// "系统将于今晚24:00进行维护升级"

JSON数据处理示例

const xhr2 = new XMLHttpRequest();
xhr2.open('GET', '/api/user/123', true);
xhr2.onload = function() {
  console.log('\n示例2 - JSON原始数据:');
  console.log(xhr2.responseText);
  
  const user = JSON.parse(xhr2.responseText);
  console.log('解析后对象:', user);
};
xhr2.send();
// 输出可能:
// {"id":123,"name":"张三","age":28}
// 解析后对象: {id: 123, name: "张三", age: 28}

HTML片段处理示例

const xhr3 = new XMLHttpRequest();
xhr3.open('GET', '/widget/news', true);
xhr3.onload = function() {
  console.log('\n示例3 - HTML片段:');
  console.log(xhr3.responseText);
  
  document.getElementById('news-box')
    .innerHTML = xhr3.responseText;
};
xhr3.send();
// 输出可能:
// <div class="news-item"><h3>今日要闻</h3><p>经济持续向好...</p></div>

大文本数据示例

const xhr4 = new XMLHttpRequest();
xhr4.open('GET', '/large-text', true);
xhr4.onprogress = function(e) {
  console.log(`已接收: ${e.loaded}字节`);
};
xhr4.onload = function() {
  console.log('\n示例4 - 大文本统计:');
  console.log(`总长度: ${xhr4.responseText.length}字符`);
  console.log(`前100字符: ${xhr4.responseText.substring(0,100)}...`);
};
xhr4.send();
// 输出可能:
// 已接收: 102400字节
// 已接收: 204800字节
// 总长度: 356812字符
// 前100字符: 第一章 总则 第一条 为了规范...

错误处理示例

const xhr5 = new XMLHttpRequest();
xhr5.open('GET', '/api/non-existent', true);
xhr5.onload = function() {
  if(xhr5.status === 404) {
    console.log('\n示例5 - 错误响应:');
    console.log('错误内容:', xhr5.responseText);
  }
};
xhr5.send();
// 输出可能:
// 错误内容: {"error":"Not Found","message":"请求资源不存在"}

实时数据流示例

const xhr6 = new XMLHttpRequest();
xhr6.open('GET', '/stream', true);
xhr6.onreadystatechange = function() {
  if(xhr6.readyState === 3) {
    console.log('\n示例6 - 实时数据:');
    console.log('部分数据:', xhr6.responseText);
  }
};
xhr6.send();
// 输出可能(多次):
// 部分数据: 当前时间:2025-08-31 19:45:00
// 部分数据: 当前时间:2025-08-31 19:45:00\nCPU使用率:32%

标签: