文章内容

2022/12/19 10:01:08,作 者: 黄兵

JavaScript XMLHttpRequest fetch 发送 HTTP 请求示例

有几种方法可以在 JavaScript 中进行 HTTP 请求。最常见的方法之一是使用 XMLHttpRequest 对象。这个对象在所有的现代浏览器中都被支持,并允许你从 JavaScript 中发送 HTTP 请求。

下面是一个如何使用 XMLHttpRequest 对象进行 GET 请求的例子:

// Create a new XMLHttpRequest object
var xhr = new XMLHttpRequest();

// Set the HTTP method and URL
xhr.open('GET', 'https://pdf-lib.org');

// Set the callback function
xhr.onload = function() {
  // This is called even on 404 etc
  // so check the status
  if (xhr.status != 200) {
    console.error(xhr.status + ': ' + xhr.statusText);
  } else {
    // Show the result
    console.log(xhr.responseText);
  }
};

// Send the request
xhr.send();

我们也可以使用 XMLHttpRequest 对象进行 POST 请求,方法是使用 POST HTTP 方法的 open 方法,并根据你要发送的数据格式,将 Content-Type 请求头设置为 application/x-www-form-urlencodedmultipart/form-data 。下面是一个用表单数据进行 POST 请求的例子:

var xhr = new XMLHttpRequest();

xhr.open('POST', 'https://pdf-lib.org/submit');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

xhr.onload = function() {
  if (xhr.status != 200) {
    console.error(xhr.status + ': ' + xhr.statusText);
  } else {
    console.log(xhr.responseText);
  }
};

var formData = 'name=Josiah&age=28';
xhr.send(formData);

在 JavaScript 中进行 HTTP 请求的另一种方法是使用 fetch 函数,它是 XMLHttpRequest 对象的一个现代替代品。fetch 函数在所有的现代浏览器中都被支持,它允许你用更简洁、更容易使用的语法来进行 HTTP 请求。下面是一个如何使用 fetch 函数进行 GET 请求的例子。

fetch('https://pdf-lib.org')
  .then(response => response.text())
  .then(data => console.log(data))
  .catch(error => console.error(error));

你也可以通过传递一个 options 对象作为第二个参数,使用 fetch 函数进行 POST 请求。在选项对象中,你可以把 method 属性设置为 POST,把正文属性设置为你想发送的数据。下面是一个使用 fetch 函数发出带有表单数据的 POST 请求的例子:

fetch('https://pdf-lib.org/submit', {
  method: 'POST',
  body: 'name=Josiah&age=28',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
})
  .then(response => response.text())
  .then(data => console.log)

总结

这篇给文章通过 XMLHttpRequest 和 fetch 发送 HTTP 请求,并且通过两个示例讲解了其使用方法,是不是很简单。

如果有任何问题,欢迎下面留言。

分享到:

发表评论

评论列表