iT邦幫忙

2021 iThome 鐵人賽

DAY 22
0
自我挑戰組

Be friend with JavaScript系列 第 22

Day 22 - Ajax

Ajax ( Asynchronous JavaScript and XML )
網頁不用重新整理,就能即時地透過瀏覽器去跟伺服器溝通,撈出資料

Request & Response

request - 發出請求
response - 資料回傳

request 發出請求時,資料會顯示在 request headers,含來源位置 & 網址及瀏覽器資料等(表明身分)。
response 資料回傳後,會回傳 response headers 和 response data,response headers 不會顯示在網頁上,真正回傳的資料顯示在 response data 裡,且 response data 要被編譯成什麼格式,由 response headers 裡的 Content-type 來決定。

常見 Content-type 格式

  • application/x-www-form-urlencoded : (表單格式)
  • application/json : (json格式 )
  • multipart/form-data : 檔案格式(pdf/word/圖片/mp4),傳送文件使用
  • text/plain : 記事本格式(不常用)
  • text/html : HTML格式

XMLHttpRequest

(這是古老的用法,後面的文章會陸續介紹其他更好用的方法)

用法:

  • 建立 xhr 物件
    XMLHttpRequest 物件裡面有很多方法跟特性可以做應用,例如 onload,readyState。
let xhr = new XMLHttpRequest();
console.log(xhr) // 此時會是空物件
// 此時狀態 readyState0 - 已經產生了 XMLHttpRequest 但還沒連結要撈的資料

readyState
0 - client 端已被建立,但 open() 方法尚未被呼叫。
1 - open() 方法已被呼叫。
2 - send() 方法已被呼叫,發出請求,但還沒收到回應。
3 - 已收到部分回應,此時 responseText 會擁有部分資料。
4 - 表示資料已全部接收到,狀態為 4 時,就可以把資料顯示到網頁上了。

  • open() 設定請求
    xhr.open('方法', '網址', true/false);
    第一個參數: 方法,get/post/put/delete...等
    第二個參數: api網址
    第三個參數: 同步(false)與非同步(true),不填則預設為非同步 true
    非同步 true - 不等資料程式碼就繼續往下跑,等回傳才自動回傳
    同步 false - 等資料傳回來
xhr.open('get','https://randomuser.me/api/?results=1',true)
// 此時狀態 readyState1 - 用了open 但還沒把資料傳過去
  • 傳送請求
    xhr.send();
xhr.send(null) // 只是要讀取資料 所以傳送 null
// 此時狀態readyState4 - 代表已經撈到資料,數據完全接收到了,此時 response 裡已經有資料
  • 要注意,open()的第三個參數若是非同步,就要使用 onload
let xhr = new XMLHttpRequest();
xhr.open('get','https://randomuser.me/api/?results=1',true)
xhr.send(null)

因為 open 裡面參數是 true 會顯示 undefined,抓不到資料,這時候就要利用 onload,等網頁跑完再觸發事件內容

xhr.onload = function(){
  console.log(xhr.response)}

HTTP狀態

  • 200:資料正確回傳
  • 404:資料讀取錯誤
  • 304:記憶體有快取起來了(清除快取重新載入後就不會看到304)
  • 500:伺服器錯誤

使用 RANDOM USER API 實作

let url = "https://randomuser.me/api/?results=1";
let xhr = new XMLHttpRequest();
xhr.open('get',url,true);
xhr.send(null);
xhr.onload = function(){
  console.log(JSON.parse(xhr.response));
}

這時候得到的 JSON 資料會長這樣
https://ithelp.ithome.com.tw/upload/images/20210924/20140282YiPiQblsWW.png
成功取得一筆隨機資料,這時候使用 F12 查看會看到 status 顯示 200

Cross-Origin Resource Sharing (CORS)

開了CORS權限,其他開發者才能跨網域撈取資料,若開發者沒有開權限,則xhr的status會顯示0,沒辦法取得資料(有時會因為資安問題選擇不開)
想知道某筆資料(JSON 或 API)有沒有開 CORS,可以上 test-cros.org 查詢。
XHR status:200 - 表示資料可取得

XHR status:0 - 表示無開放CORS權限

參考資料:
XMLHttpRequest.readyState
XMLHttpRequest MDN


上一篇
Day 21 - Class
下一篇
Day 23 - Promise
系列文
Be friend with JavaScript39
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言