JavaScript Day20 - AJAX(2)

ES6:fetch

  • fetch():Fetch API 提供了一个能获取包含跨网路资源在的资源介面,功能类似前一天XMLHttpRequest ,但更容易使用,是我目前比较常用的 AJAX 方法
    • fetch():放 request,基本上就是 url,其他的若需要如 post 则用 {} 将 method、body、headers 之类的放入
    • then(response):response 的结果,如果是 JSON 一般会用 .json() 解析,其他还有文字 .text()
    • then():取得解析後的资料要做的事情,例如改变你的网页内容
    • catch(err):错误时的状况

语法与 JSON 例子

fetch('http://example.com/', {method: 'get'})
  .then(function(response) {
    //处理 response
  }).catch(function(err) {
    // Error
});

// JSON
fetch('http://example.com/movies.json')
  .then(function(response) {
    return response.json();
  })
  .then(function(myJson) {
    console.log(myJson);
  }).catch(function(err) {
    console.log(err);
});

POST 方法

// post
const url = '';  // API url
const data = {
  "name": name.value,
  "password": password.value
}; // JSON data

fetch(url,{
  method:'POST',
  body:JSON.stringify(data),
  headers: {'Content-Type': 'application/json'}
  }).then() // function 

参考资料

MDN Fetch API
MDN Using Fetch
AJAX与Fetch API
铁人赛:ES6 原生 Fetch 远端资料方法
JacaScript | Fetch 让 ES6 拥有一对翅膀-基础教学
JavaScript Fetch API 使用教学

次回

还是会再说明 AJAX


<<:  #20 数据中的机率性(1)

>>:  用 Python 畅玩 Line bot - 01:line channel 建立

找LeetCode上简单的题目来撑过30天啦(DAY10)

终於第十天了呀,我觉得要撑满30天好难,奇怪了我为甚麽要这麽勉强自己,压力爆棚压 题号:75 标题:...

[第二十天]从0开始的UnityAR手机游戏开发-介绍Animator02

本次将延续前一章节的教学 点选Cube Animation往CubeAttack Animation...

[Day 30] 终於结束了OMG

刚开始一定要先恭喜自己,我完成了!! 再发第一天文之前完全不觉得自己有办法可以胜任这个挑战,没想到我...

前端工程学习日记第三天

小技巧:ul>li*3 打出来 可以用emmet快速做出 昨日疑问:我的HTML为何没有快速工...

test

test 这是H4标题 ...