在JavaScript中,可以使用原生的XMLHttpRequest对象或者更现代的fetch API来发送AJAX请求。以下是使用XMLHttpRequest对象和fetch API的简单例子。
使用XMLHttpRequest:
function makeRequest(method, url, data, callback) {
  const xhr = new XMLHttpRequest();
  xhr.open(method, url, true);
  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
      callback(xhr.responseText);
    }
  };
  if (method === 'POST') {
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.send(data);
  } else {
    xhr.send();
  }
}
 
// 使用方法:
makeRequest('GET', 'https://api.example.com/data', null, function(response) {
  console.log(response);
});
使用fetch API:
function makeRequest(method, url, data) {
  const fetchOptions = {
    method: method,
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  };
  if (method === 'POST') {
    fetchOptions.body = data;
  }
  return fetch(url, fetchOptions)
    .then(response => {
      if (!response.ok) {
        throw new Error('Network response was not ok ' + response.statusText);
      }
      return response.text();
    })
    .then(data => {
      console.log(data);
    })
    .catch(error => {
      console.error('There has been a problem with your fetch operation:', error);
    });
}
 
// 使用方法:
makeRequest('GET', 'https://api.example.com/data').then(() => {
  // 处理响应
});
这两个例子都展示了如何发送AJAX请求,并在请求成功后处理响应。XMLHttpRequest是较旧的方法,而fetch API是现代浏览器中更为现代和强大的方式。两者都可以用于包装AJAX请求,以便在代码库中更广泛地使用。