function ajaxRequest(method, url, data, callback) {
var xhr = new XMLHttpRequest();
xhr.open(method, url, true);
if (method === 'POST') {
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
}
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
callback(xhr.responseText);
}
};
if (method === 'POST') {
xhr.send(data);
} else {
xhr.send();
}
}
// 使用示例
ajaxRequest('GET', 'https://example.com/data', null, function(response) {
console.log(response);
});
ajaxRequest('POST', 'https://example.com/submit', 'key1=value1&key2=value2', function(response) {
console.log(response);
});
在上述代码中:
例如,在上面的使用示例中,分别进行了 GET 和 POST 请求,并在回调函数中打印响应的文本内容。