"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 ticks=0;const timer=setInterval(()=>document.querySelector('#ticks').textContent=String(++ticks),30);
document.querySelector('#run').onclick=()=>{
const xhr=new XMLHttpRequest();const start=performance.now();
try{xhr.open('GET','/api/slow?ms=300',false);xhr.send();show({status:xhr.status,text:xhr.responseText,elapsedMs:performance.now()-start});}
catch(error){show(error.name+': '+error.message);}
};
window.addEventListener('pagehide',()=>clearInterval(timer));
本例需在 独立本地HTTP页面;浏览器同步XHR策略可能限制,禁止在正式业务流使用 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:独立本地HTTP页面;浏览器同步XHR策略可能限制,禁止在正式业务流使用
入口文件:projects/ajax-lab/public/examples/xhr-sync.html
本例采用完整 HTML 文档,样式和脚本在 HTML 源码中维护。
预期结果与验证条件观察提示
- 允许同步请求的独立环境中send返回前主线程计数暂停,返回后显示状态与耗时
- 浏览器若阻止该历史能力,应记录实际异常;不能以此推断异步请求失败
请结合实际环境逐项观察。
附件与关联工程包下载
课程关联工程包(登记关联13章) · 含当前章节或实例 · mbskycom202611a180.zip