使用JavaScript可以通过内置的XMLHttpRequest对象或者更现代的fetch函数来发出HTTP请求。

使用XMLHttpRequest发送GET请求

以下代码展示了如何使用XMLHttpRequest对象发出GET请求:

const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true);  // 发起GET请求到指定URL
xhr.onreadystatechange = function() {
    if (xhr.readyState === 4 && xhr.status === 200) {  // 请求成功
        const response = JSON.parse(xhr.responseText);
        console.log(response);  // 处理响应数据
    }
};
xhr.send();  // 发送请求

使用Fetch API发送GET请求

使用fetch函数发出GET请求更加简洁:

fetch('https://api.example.com/data')
    .then(response => response.json())  // 解析响应数据为JSON格式
    .then(data => console.log(data))  // 处理响应数据
    .catch(error => console.log(error));  // 处理错误

使用Fetch API发送POST请求

以下代码演示了如何使用fetch函数发送POST请求,包括设置请求头和请求体:

const data = { username: 'example', password: 'password' };
fetch('https://api.example.com/login', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify(data)  // 将数据转换为JSON字符串
})
.then(response => response.json())  // 解析响应数据为JSON格式
.then(data => console.log(data))  // 处理响应数据
.catch(error => console.log(error));  // 处理错误

注意: 以上代码仅为示例,实际使用时需要替换URL和请求数据,并根据API的要求设置请求头等。

JavaScript发送HTTP请求完全指南:从XMLHttpRequest到Fetch API

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

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