function makeRequest(method, url, data, callback) {
var xhr = new XMLHttpRequest();
xhr.open(method, url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var response = JSON.parse(xhr.responseText);
callback(response);
}
};
if (method === 'GET') {
xhr.send();
} else if (method === 'POST') {
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(data);
}
}
// 使用封装后的函数发送请求
makeRequest('GET', 'your-api-endpoint', null, function (response) {
console.log(response);
});
makeRequest('POST', 'your-api-endpoint', 'key1=value1&key2=value2', function (response) {
console.log(response);
});
Ajax封装
最新推荐文章于 2024-08-08 17:09:09 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)