以下是使用 JavaScript 原生的 XMLHttpRequest 对象进行 ajax 请求的示例代码:

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);
});

在上述代码中:

  • ajaxRequest 函数接受请求方法(method)、请求
    URL(url)、要发送的数据(data)和回调函数(callback)作为参数。
  • 通过 open 方法设置请求的方法和 URL,并指定是否异步。 根据请求方法设置相应的请求头。
  • 通过 onreadystatechange 事件监听请求状态的变化,当请求完成且状态码为 200 时,调用回调函数处理响应数据。
  • 最后根据请求方法发送数据。

例如,在上面的使用示例中,分别进行了 GET 和 POST 请求,并在回调函数中打印响应的文本内容。

07-18 06:59