Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

javascript fetch

作者:靈魂风尖上   发布日期:2025-09-21   浏览:55

// 使用 fetch API 发起 GET 请求的示例

fetch('https://api.example.com/data')
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json(); // 将响应体解析为 JSON 格式
  })
  .then(data => {
    console.log(data); // 处理从服务器返回的数据
  })
  .catch(error => {
    console.error('There has been a problem with your fetch operation:', error);
  });

// 使用 fetch API 发起 POST 请求的示例

const postData = {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    title: 'foo',
    body: 'bar',
    userId: 1,
  }),
};

fetch('https://jsonplaceholder.typicode.com/posts', postData)
  .then(response => response.json()) // 将响应体解析为 JSON 格式
  .then(data => {
    console.log(data); // 处理从服务器返回的数据
  })
  .catch(error => {
    console.error('There has been a problem with your fetch operation:', error);
  });

解释说明:

  • fetch 是一个用于发起网络请求的现代 JavaScript API。它返回一个 Promise,该 Promise 会在请求完成时解析为 Response 对象。
  • response.ok 检查 HTTP 状态码是否在 200-299 之间,表示请求成功。
  • response.json() 方法将响应体解析为 JSON 格式。
  • catch 块用于捕获并处理可能发生的错误。
  • 在发起 POST 请求时,需要指定请求方法、请求头和请求体。

上一篇:javascript 数组

下一篇:javascript字符串转换为数字

大家都在看

js 数组对象排序

js 数组删掉第一个值

js fill

js 数组连接

js json数组

js 数组复制

js 复制数组

js 数组拷贝

js 对象数组合并

js 对象转数组

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站