在 JavaScript 中,你可以使用内置的 XMLHttpRequest 对象或使用现代的 Fetch 函数来发送 HTTP 请求。

使用 XMLHttpRequest 对象的示例代码如下:

var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true);
xhr.onreadystatechange = function () {
  if (xhr.readyState === 4 && xhr.status === 200) {
    var response = JSON.parse(xhr.responseText);
    console.log(response);
  }
};
xhr.send();

使用 Fetch 函数的示例代码如下:

fetch('https://api.example.com/data')
  .then(function (response) {
    return response.json();
  })
  .then(function (data) {
    console.log(data);
  })
  .catch(function (error) {
    console.log(error);
  });

这些代码示例演示了如何发送一个简单的 GET 请求,你可以替换 URL 以及请求方法(GET、POST 等)来适应你的需求。请注意,在实际应用中,你可能需要处理错误、设置请求头、发送 POST 请求等。

JavaScript 发送 HTTP 请求:XMLHttpRequest 和 Fetch API

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

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