当前位置: 首页> 科技> 互联网 > 博罗网站设计公司_个人网站开发流程_微商引流人脉推广软件_源码之家

博罗网站设计公司_个人网站开发流程_微商引流人脉推广软件_源码之家

时间:2025/7/11 9:29:09来源:https://blog.csdn.net/weixin_43063398/article/details/146021290 浏览次数:0次
博罗网站设计公司_个人网站开发流程_微商引流人脉推广软件_源码之家

XMLHttpRequest

get请求使用

const xhr = new XMLHttpRequest();
xhr.open("GET", "/data/test.json", true);
xhr.onreadystatechange = function () {if (xhr.readyState === 4) {if (xhr.status === 200) {alert(xhr.responseText);} else {console.log("其他情况");}}
};xhr.send(null);

post请求

const xhr = new XMLHttpRequest();
xhr.open("POST", "/data/test.json", true);
xhr.onreadystatechange = function () {if (xhr.readyState === 4) {if (xhr.status === 200) {alert(xhr.responseText);} else {console.log("其他情况");}}
};const postData = {userName: "zhangsan",password: "xxx",
};xhr.send(JSON.stringify(postData));

xhr.readyState

用的最多的还是4

 xhr.status

手写AJAX

function myAjax(url, method = "GET", data = null, headers = {}) {return new Promise((resolve, reject) => {const xhr = new XMLHttpRequest();xhr.open(method, url, true);for (const [key, value] of Object.entries(headers)) {xhr.setRequestHeader(key, value);}xhr.onreadystatechange = function () {if (xhr.readyState === 4) {if (xhr.status >= 200 && xhr.status < 300) {try {const response = xhr.responseText? JSON.parse(xhr.responseText): null;resolve(response);} catch (error) {reject(new Error("JSON解析失败"));}} else {const errorMap = {400: "请求参数错误",401: "未授权",403: "禁止访问",404: "资源未找到",500: "服务器内部错误",};reject(new Error(errorMap[xhr.status] || `请求失败,状态码:${xhr.status}`));}}};xhr.send(method.toUpperCase() === "GET" ? null : data);});
}

ajax的常见使用

  • 传统 XMLHttpRequest:兼容性好,适合旧项目。

  • Fetch API:现代、简洁,推荐用于新项目。

  • Axios:功能强大,适合企业级应用。

存储

cookie

 缺点

localStorage和sessionStorage

区别

关键字:博罗网站设计公司_个人网站开发流程_微商引流人脉推广软件_源码之家

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: