上一篇
XMLHttpRequest对象
原生AJAX的核心API,用于创建异步请求。
请求步骤
const xhr = new XMLHttpRequest();
xhr.open(method, url, async)
参数:请求方法(GET/POST)、URL、是否异步(默认true)。
xhr.setRequestHeader('Content-Type', 'application/json')
xhr.send(body)
(GET请求时body为null
) xhr.onreadystatechange
或 xhr.onload
事件与状态码
readyState
:请求状态(0-4,4表示完成)。 status
:HTTP响应状态码(如200成功、404未找到)。 响应处理
xhr.responseText
xhr.responseXML
xhr.onerror
兼容性
ActiveXObject
。 POST请求示例
const xhr = new XMLHttpRequest(); xhr.open('POST', '/api', true); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.onload = () => { if (xhr.status === 200) console.log(xhr.responseText); }; xhr.send(JSON.stringify({ key: 'value' }));
GET请求示例
const xhr = new XMLHttpRequest(); xhr.open('GET', '/api?id=123', true); xhr.onload = () => { if (xhr.status === 200) console.log(xhr.responseText); }; xhr.send();
优缺点
如需进一步简化,可结合现代fetch API
或框架(如Axios)。
本文由 完丹亦 于2025-08-02发表在【云服务器提供商】,文中图片由(完丹亦)上传,本平台仅提供信息存储服务;作者观点、意见不代表本站立场,如有侵权,请联系我们删除;若有图片侵权,请您准备原始证明材料和公证书后联系我方删除!
本文链接:https://vps.7tqx.com/wenda/512758.html
发表评论