Javascript 中发出 HTTP 请求

要在 JavaScript 中发出 HTTP 请求,您可以使用 XMLHttpRequest 对象或 fetch() 函数。

下面是使用 XMLHttpRequest 发出 GET 请求的示例:

const xhr = new XMLHttpRequest();

xhr.open('GET', 'https://example.com/api/endpoint');

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

xhr.send();

下面是使用 fetch() 发出 GET 请求的示例:

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

两个示例都会向指定的 URL 发出 GET 请求,并将响应记录到控制台。 fetch() 示例使用 Promises,这是处理 JavaScript 中的异步操作的一种方法。

您还可以通过指定适当的方法(例如 POST)并根据需要添加请求正文来使用这些方法发出 POST、PUT、DELETE 和其他类型的请求。

 使用JavaScript发送POST请求,可以使用XMLHttpRequest对象。这里是使用XMLHttpRequest发送POST请求到服务器的例子:

// Create an instance of the XMLHttpRequest object
var xhr = new XMLHttpRequest();

// Set the HTTP method and URL of the request
xhr.open("POST", "https://example.com/api/endpoint");

// Set the request header
xhr.setRequestHeader("Content-Type", "application/json");

// Set a function to be called when the request is complete
xhr.onload = function () {
  // Check the status of the response
  if (xhr.status === 200) {
    // If the request was successful, parse the response text as JSON
    var response = JSON.parse(xhr.responseText);
    // Do something with the response
  } else {
    // If the request was unsuccessful, log an error message
    console.error("An error occurred: " + xhr.status);
  }
};

// Set the request body
var data = {
  field1: "value1",
  field2: "value2",
};

// Send the request
xhr.send(JSON.stringify(data));

此代码创建 XMLHttpRequest 对象的实例,设置请求的 HTTP 方法和 URL,设置请求标头,并定义请求完成时要调用的函数。该函数检查响应的状态,并将响应文本解析为 JSON(如果请求成功)或记录错误消息(如果请求不成功)。请求正文设置为对象,并使用 send() 方法发送请求,将请求正文作为字符串化的 JSON 对象传入。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值