使用 JavaScript 发出 HTTP 请求可以使用内置的'XMLHttpRequest' 对象或者'fetch' API。以下是使用这两种方法之一的示例:

使用'XMLHttpRequest' 对象:

function makeHttpRequest(url, method, data, callback) {
  var xhr = new XMLHttpRequest();
  xhr.open(method, url, true);
  xhr.setRequestHeader('Content-Type', 'application/json');
  
  xhr.onreadystatechange = function() {
    if (xhr.readyState === 4 && xhr.status === 200) {
      var response = JSON.parse(xhr.responseText);
      callback(response);
    }
  };
  
  xhr.send(JSON.stringify(data));
}

使用'fetch' API:

function makeHttpRequest(url, method, data, callback) {
  fetch(url, {
    method: method,
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(data)
  })
  .then(function(response) {
    return response.json();
  })
  .then(function(responseData) {
    callback(responseData);
  });
}

以上两个函数都接受四个参数:

  • 'url':请求的URL地址。
  • 'method':请求的方法,例如'GET'、'POST'等。
  • 'data':可选参数,如果需要发送数据给服务器,则将数据作为JavaScript对象传递给此参数。
  • 'callback':回调函数,用于处理服务器响应数据。

你可以使用以上函数来发出HTTP请求并处理响应。确保将适当的URL、请求方法和数据传递给这些函数。

JavaScript HTTP 请求:XMLHttpRequest 与 Fetch API 详解

原文地址: https://www.cveoy.top/t/topic/osp 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录