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 方法发送请求体数据。