在 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 = xhr.responseText;
        console.log(response);
    }
};
xhr.send();

使用 'fetch' 函数:

fetch('https://api.example.com/data')
    .then(function(response) {
        if (response.ok) {
            return response.text();
        }
        throw new Error('Request failed.');
    })
    .then(function(data) {
        console.log(data);
    })
    .catch(function(error) {
        console.log(error);
    });

以上代码示例了如何发出 GET 请求并处理响应。你可以根据需要调整请求方法(GET、POST 等)和 URL。请确保替换示例中的 URL 为你要请求的实际 URL。


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

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