前端手写代码面试题
目录

实现一个函数 ajax(options),发送 AJAX 请求

· 约 4 分钟读完 · 第 76 / 125 章

推荐答案

本题详细解读

1. 函数参数

  • options: 一个包含请求配置的对象,包含以下属性:
    • url: 请求的URL地址。
    • method: 请求方法,默认为 'GET'。
    • data: 请求体数据,默认为 null。
    • headers: 请求头对象,默认为空对象 {}。
    • success: 请求成功时的回调函数。
    • error: 请求失败时的回调函数。

2. 创建 XMLHttpRequest 对象

  • 使用 new XMLHttpRequest() 创建一个新的 XMLHttpRequest 对象。

3. 打开请求

  • 使用 xhr.open(method, url, true) 初始化请求。method 是请求方法,url 是请求地址,true 表示异步请求。

4. 设置请求头

  • 遍历 headers 对象,使用 xhr.setRequestHeader(key, headers[key]) 设置请求头。

5. 处理响应

  • 使用 xhr.onload 监听请求完成事件。如果状态码在 200 到 299 之间,表示请求成功,调用 success 回调函数并传入响应文本 xhr.responseText。否则,调用 error 回调函数并传入状态文本 xhr.statusText。

6. 处理错误

  • 使用 xhr.onerror 监听请求错误事件。如果发生网络错误,调用 error 回调函数并传入 'Network Error'。

7. 发送请求

  • 使用 xhr.send(data) 发送请求。data 是请求体数据,如果为 null 或 undefined,则不发送请求体。

8. 使用示例