使用 JavaScript 发出 HTTP 请求的一种常见方式是使用内置的 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:', error);
    });

以上两种方法都是异步的,可以通过回调函数或 Promise 来处理响应数据。请注意,这只是发出 GET 请求的简单示例,可以根据需要进行调整和扩展。

JavaScript HTTP 请求:XMLHttpRequest 和 fetch API

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

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