要使用 Javascript 发出 HTTP 请求,您可以使用内置的XMLHttpRequest对象或fetch()函数。下面是使用这两种方法之一的示例:

使用 XMLHttpRequest:

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

使用 fetch():

fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.log(error));

这些示例演示了如何发出一个简单的 GET 请求。您可以根据需要进行自定义,例如使用 POST 方法、设置请求头、传递参数等。

JavaScript HTTP 请求: 使用 XMLHttpRequest 和 fetch() 发送请求

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

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