使用原生JS XMLHttpRequest发送网络请求
原生JS提供了XMLHttpRequest对象来发送和接收HTTP请求的接口。
GET 请求例:
var xhr = new XMLHttpRequest()
xhr.open('GET', 'https://api.example.com/data', true)
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
var response = JSON.parse(xhr.responseText)
console.log(response)
}
}
xhr.send()
以上代码创建了一个XMLHttpRequest对象,并调用open方法指定请求的URL和请求类型为GET。然后通过onreadystatechange事件监听请求状态的变化,在请求完成且状态码为200时,通过JSON.parse解析响应数据并进行处理。
POST 请求例:
var xhr = new XMLHttpRequest()
xhr.open('POST', 'https://api.example.com/data', true)
xhr.setRequestHeader('Content-Type', 'application/json')
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
var response = JSON.parse(xhr.responseText)
console.log(response)
}
}
xhr.send(JSON.stringify({ key: 'value' }))
以上代码与GET请求类似,只是在open方法中指定请求的类型为POST,并通过setRequestHeader方法设置请求头的Content-Type为application/json,然后通过send方法发送请求体数据。
封装发送方法
为了提高代码的复用性和可维护性,我们可以对XMLHttpRequest进行封装,以更便捷地发送网络请求。
封装 GET 请求例:
function getRequest(url, successCallback, errorCallback) {
var xhr = new XMLHttpRequest()
xhr.open('GET', url, true)
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
var response = JSON.parse(xhr.responseText)
successCallback && successCallback(response)
} else {
errorCallback && errorCallback(xhr.statusText)
}
}
}
xhr.send()
}
以上代码定义了一个 getRequest 函数,接受三个参数:请求的URL、请求成功的回调函数和请求失败的回调函数。在函数内部,首先创建一个 XMLHttpRequest 对象,并调用 open 方法设置请求的 URL 和请求类型为 GET 。然后通过 onreadystatechange 事件监听请求状态的变化,当请求完成并且状态码为 200 时,通过 JSON.parse 解析响应数据,并调用成功回调函数。如果请求失败,则调用失败回调函数,并传入状态描述。
封装 POST 请求例:
function postRequest(url, data, successCallback, errorCallback) {
var xhr = new XMLHttpRequest()
xhr.open('POST', url, true)
xhr.setRequestHeader('Content-Type', 'application/json')
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
var response = JSON.parse(xhr.responseText)
successCallback && successCallback(response)
} else {
errorCallback && errorCallback(xhr.statusText)
}
}
}
xhr.send(JSON.stringify(data))
}
以上代码定义了一个 postRequest 函数,除了 URL 和回调函数外,额外接受一个 data 参数用于指定 POST 请求的数据。在函数内部,与发送 GET 请求类似,只是调用 open 方法时设置请求的类型为 POST ,并通过 setRequestHeader 方法设置请求头的 Content-Type 为 application/json ,然后将 data 参数转为 JSON 字符串并通过 send 方法发送请求体数据。
总结原生JS XMLHttpRequest 对象发送网络请求的方法,并封装发送方法以提高代码的复用性和可维护性。使用原生JS可以灵活地控制请求的方式和参数,并处理响应数据。
以上示例代码展示了原生发送方法和封装发送方法的用法