XMLHttpRequest 发送请求
小于 1 分钟
XMLHttpRequest 是一个内建的浏览器对象,它允许使用 JavaScript 发送 HTTP 请求。
虽然它的名字里面有 “XML” 一词,但它可以操作任何数据,而不仅仅是 XML 格式。我们可以用它来上传/下载文件,跟踪进度等。
现如今,我们有一个更为现代的方法叫做 fetch,它的出现使得 XMLHttpRequest 在某种程度上被弃用。
在现代 Web 开发中,出于以下三种原因,我们还在使用 XMLHttpRequest:
历史原因:我们需要支持现有的使用了 XMLHttpRequest 的脚本。 我们需要兼容旧浏览器,并且不想用 polyfill(例如为了使脚本更小)。 我们需要做一些 fetch 目前无法做到的事情,例如跟踪上传进度。
/*
* File Created: Thursday, 20th April 2023 5:00:08 pm
* Author: hotsuitor (hotsuitor@qq.com)
* -----
* Last Modified: Thursday, 20th April 2023 5:00:41 pm
* Modified By: hotsuitor (hotsuitor@qq.com>)
*/
/**
*
* @param {Object} options
* @param {string} options.url
* @param {string} options.method
* @param {Object} options.data
* @param {Function} options.success
* @param {Function} options.error
*/
function request(options = {}) {
// 初始化xhr实例
let xhr = new XMLHttpRequest()
method = options.method ? options.method.toUpperCase() : 'GET'
if (method === 'POST') {
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencode')
}
xhr.open(method, options.url, true)
xhr.send(method === 'GET' ? null : JSON.stringify(options.data))
xhr.onreadystatechange = function () {
// UNSENT = 0; // 初始状态
// OPENED = 1; // open 被调用
// HEADERS_RECEIVED = 2; // 接收到 response header
// LOADING = 3; // 响应正在被加载(接收到一个数据包)
// DONE = 4; // 请求完成
if (xhr.readyState === 4) {
if (typeof options.success === 'function') {
options.success(xhr.response || xhr.responseText)
}
} else {
console.warn('request failed')
if (typeof options.error === 'function') {
options.error(xhr.responseText)
}
}
}
xhr.onerror = function () {
// 处理非 HTTP error(例如网络中断)
console.error('Network Error')
}
}
request({ url: 'https://www.baidu.com' }, (res) => {
console.log(res)
})