在开发过程中,网络请求是获取数据、实现前后端交互的重要手段。JavaScript 作为前端开发的核心语言,提供了多种发送网络请求的方法。本文将详细介绍 JavaScript 中 GET 和 POST 请求的发送方法,以及如何解析响应数据。

GET 请求

GET 请求是最常见的 HTTP 请求方法之一,用于请求数据。以下是使用 JavaScript 发送 GET 请求的几种方法:

1. 使用 XMLHttpRequest

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

2. 使用 fetch API

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

3. 使用 axios

axios.get('https://api.example.com/data')
  .then(response => console.log(response.data))
  .catch(error => console.error('Error:', error));

POST 请求

POST 请求用于向服务器发送数据,常用于表单提交等场景。以下是使用 JavaScript 发送 POST 请求的几种方法:

1. 使用 XMLHttpRequest

var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://api.example.com/data', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function () {
  if (xhr.readyState === 4 && xhr.status === 200) {
    console.log(xhr.responseText);
  }
};
xhr.send(JSON.stringify({ key: 'value' }));

2. 使用 fetch API

fetch('https://api.example.com/data', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({ key: 'value' })
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

3. 使用 axios

axios.post('https://api.example.com/data', { key: 'value' })
  .then(response => console.log(response.data))
  .catch(error => console.error('Error:', error));

响应数据解析

在发送请求后,我们需要解析服务器返回的数据。以下是几种常见的响应数据类型:

1. JSON

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

2. XML

fetch('https://api.example.com/data')
  .then(response => response.text())
  .then(data => {
    const parser = new DOMParser();
    const xml = parser.parseFromString(data, 'text/xml');
    console.log(xml.getElementsByTagName('item')[0].textContent);
  })
  .catch(error => console.error('Error:', error));

3. Text

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

总结

本文介绍了 JavaScript 中发送 GET 和 POST 请求的方法,以及如何解析响应数据。在实际开发中,根据需求选择合适的方法和响应数据解析方式,可以有效提高开发效率。希望本文能帮助您轻松上手掌握网络请求与数据解析技巧。